Alw*_*ing 2 c++ policy-based-design c++11
假设一个具有策略的算法FooPolicy.实现此策略的策略类具有静态成员函数foo,但是,对于其中一些,foo采用int参数,而对于其他策略类则不会.我试图通过constexpr静态数据成员启用这些具有不同接口的策略类:
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;
}
Run Code Online (Sandbox Code Playgroud)
此代码无法编译.gcc 4.8.2给出错误:
调用'ParamFoo :: foo()'没有匹配函数
否则FooPolicy :: foo();
该else尽管这是在编译时的已知条款被编译FooPolicy::paramFlag为true.有没有办法让它发挥作用?
有没有办法让它发挥作用?
一种解决方案是使用标签分派:
#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();
}
};
Run Code Online (Sandbox Code Playgroud)