我想编写一个具有两个模板参数的类,其中两个模板参数都是 bool 值。如果它们设置为 true,则它们都可以启用不同的额外功能。 我想实现这样的事情(这不起作用):
template<bool A, bool B>
class foo {
private:
int v1;
#if A
int v2;
#endif
public:
void f1() {}
#if B
void f2() {}
#endif
int f3() {
#if A
return v2;
#else
return v1;
#endif
}
}
如何在不造成任何性能损失的情况下实现这一目标?
最佳答案
CRTP、特化和重构:
template<typename D, bool A>
struct foo_A
{
public:
D const* self() const {
static_assert( std::is_base_of<foo_A<D,A>, D>::value, "CRTP failure" );
return static_cast<D const*>(this);
}
D* self() {
static_assert( std::is_base_of<foo_A<D,A>, D>::value, "CRTP failure" );
return static_cast<D*>(this);
}
void f3() {
return self()->v2;
}
};
template<typename D>
struct foo_A<D, true>
{
private:
int v2;
public:
D const* self() const {
static_assert( std::is_base_of<foo_A<D,A>, D>::value, "CRTP failure" );
return static_cast<D const*>(this);
}
D* self() {
static_assert( std::is_base_of<foo_A<D,A>, D>::value, "CRTP failure" );
return static_cast<D*>(this);
}
void f3() {
return self()->v1;
}
};
template<typename D, bool B> struct foo_B {};
template<typename D>
struct foo_B<D,true> {
void f2() {}
};
template<bool A, bool B>
class foo:
foo_A<foo<A,B>,A>,
foo_B<foo<A,B>,B>
{
private:
int v1;
public:
void f1() {}
};
CRTP 使您的帮助程序类能够在编译时静态访问您的类的内容,甚至其他帮助程序类。
辅助类的特化,通过适当的重构,为您提供了良好的严格条件,并且不会呈指数级增长。您甚至可以在派生类中执行一些通用逻辑,并在每个特化中访问这些值。
关于c++ - 使用模板参数更改类的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17752290/