c++ - 使用模板参数更改类的行为

标签 c++ templates template-meta-programming

我想编写一个具有两个模板参数的类,其中两个模板参数都是 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/

相关文章:

C++ 错误 : passing const as 'this' argument

c++ - 与 `if constexpr` 一起使用的编译时间消息(在预处理器之后)

c++ - 将应用程序从本地 Linux 机器移动到 Linux 服务器

c++ - 抽象函数参数格式及其对性能的影响?

c++ - Visual Studio 2008 C++。引用 DLL 项目时出现问题

c++ - 有没有办法避免在模板基类成员前面加上 `this` 前缀?

java - 如何覆盖<struts :text name ="..."/> (Struts 2 Text jsp tag) to print out the name attribute in an HTML comment?

c++ - 如何在 C++ 编译时应用 if

c++ - 将可变参数模板内容转储到二维数组

c++ - 来自 QFrame 的 Qt 气球窗口