具有不同接口的策略类 [英] Policy classes with differing interfaces
问题描述
假设有一个策略 FooPolicy
的算法。实现此策略的策略类具有静态成员函数 foo
,但是对于其中一些, foo
code> int 参数,而对于其他人则不行。我试图通过 constexpr
静态数据成员使用具有不同接口的这些策略类的使用:
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;
}
此代码不编译。 gcc 4.8.2
提供错误:
This code does not compile. gcc 4.8.2
gives the error:
ParamFoo :: foo()'
no matching function for call to ‘ParamFoo::foo()’
else FooPolicy :: foo();
else FooPolicy::foo();
else
子句被编译,尽管事实上在编译时已知 FooPolicy :: paramFlag
true
。是否有办法让它工作?
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?
推荐答案
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();
}
};
这篇关于具有不同接口的策略类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!