Policy classes with differing interfaces

拜拜、爱过 提交于 2019-12-06 08:26:32

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

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);
    }
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!