Policy classes with differing interfaces

2019-05-20 02:43发布

Suppose an algorithm that has a policy FooPolicy. Policy classes that implement this policy feature a static member function foo, but, for some of them, foo takes an int argument, while for others it does not. I am trying to enable the use of these policy classes with differing interfaces by means of constexpr static data members:

struct SimpleFoo {
    static constexpr bool paramFlag = false;
    static void foo() {
        std::cout << "In SimpleFoo" << std::endl;
    }
};

struct ParamFoo {
    static constexpr bool paramFlag = true;
    static void foo(int param) {
        std::cout << "In ParamFoo " << param << std::endl;
    }
};

template <typename FooPolicy>
struct Alg {
    void foo() {
        if (FooPolicy::paramFlag) FooPolicy::foo(5);
        else FooPolicy::foo();
    }
};

int main() {
    Alg<ParamFoo> alg;
    alg.foo();
    return 0;
}

This code does not compile. gcc 4.8.2 gives the error:

no matching function for call to ‘ParamFoo::foo()’

else FooPolicy::foo();

The else clause gets compiled despite the fact that it is known at compile time that FooPolicy::paramFlag is true. Is there a way to make it work?

2条回答
欢心
2楼-- · 2019-05-20 03:17

Is there a way to make it work?

One solution is to use tag-dispatching:

#include <type_traits>

template <typename FooPolicy>
struct Alg {
    void foo() {
        foo(std::integral_constant<bool, FooPolicy::paramFlag>{});
    }    
private:
    void foo(std::true_type) {
        FooPolicy::foo(5);
    }
    void foo(std::false_type) {
        FooPolicy::foo();
    }
};

DEMO

查看更多
三岁会撩人
3楼-- · 2019-05-20 03:33

You could dispense with the flag entirely and use expression SFINAE:

template <typename FooPolicy>
struct Alg {
    template <typename T=FooPolicy> //put FooPolicy in immediate context
    //SFINAEd out if that call is not valid
    auto foo() -> decltype(T::foo(),void()) {
        FooPolicy::foo();
    }

    template <typename T=FooPolicy>
    auto foo() -> decltype(T::foo(0),void()) {
        FooPolicy::foo(6);
    }
};
查看更多
登录 后发表回答