【问题标题】:Check template type in struct检查结构中的模板类型
【发布时间】:2019-12-12 21:40:01
【问题描述】:

我想根据模板中的类型在结构中定义其他变量,如下所示:

template<typename CONFIG>
struct Test
{
    int a;
    int b;

    if (std::is_same<CONFIG, MyClass>::value) 
    {
        // additional variables if the CONFIG type is MyClass
        int c;
        int d;
    }

    // functions
    void func()
    {
        a = 0;
        b = 0;
        if (std::is_same<CONFIG, MyClass>::value)
        {
            c = 0;
            d = 0;
        }
    }
}

我该怎么做?谢谢!

【问题讨论】:

  • 您不能在运行时修改类/结构的内容。它必须是编译时常量。
  • 您可以使用模板专业化,但不使用模板,而只需定义一个单独的 MyClassTest ,它具有额外的成员将实现同样的效果,并且复杂性更小
  • 谢谢大家!很有帮助!

标签: c++ templates struct


【解决方案1】:

这是模板专业化的一个用例。你有一个像

这样的主模板
template<typename CONFIG>
struct Test
{
    int a;
    int b;

    // functions
    void func()
    {
        a = 0;
        b = 0;
    }
};

然后是MyClass 的特化

template <>
struct Test<MyClass>
{
    int a;
    int b;
    int c;
    int d;

    // functions
    void func()
    {
        a = 0;
        b = 0;
        c = 0;
        d = 0;
    }
};

【讨论】:

  • 根据模板类型的结构是怎样的,可以通过让Test&lt;MyClass&gt;Test&lt;T&gt; 继承某些T 来减少代码重复(例如,void 可以工作)。在更困难的情况下(例如实际使用CONFIG),可以创建一个模板基类,其中包含所有模板规范通用的代码。
【解决方案2】:

一种更符合您的伪代码的变体(并不是说它比其他答案更好):

template<typename CONFIG>
struct TestAdditionalMembers {};

template<>
struct TestAdditionalMembers<MyClass>
{
    int c;
    int d;
};

template<typename CONFIG>
struct Test : TestAdditionalMembers<CONFIG>
{
    int a;
    int b;

    // functions
    void func()
    {
        a = 0;
        b = 0;
        if constexpr(std::is_same<CONFIG, MyClass>::value)
        {
            this->c = 0;
            this->d = 0;
        }
    }
};

附加成员是通过类模板的继承和显式特化提供的。由于cd 不是从属名称,而是仅针对某些模板参数存在,因此您需要使用this-&gt;c 等来引用它们(this 始终是从属名称)。

在函数内部,需要通过if constexpr 检查条件,因为运行时检查为时已晚。 (if 中的代码即使条件始终为假也必须编译。)

【讨论】:

    【解决方案3】:

    根据 walnuts 的回答,如果您想避免类型特征和 constexpr-if,您可以将所有条件操作和成员变量收集到您继承的特化中。

    template<typename T>
    struct completions {
        void func_completion() {} // does nothing
    };
    
    template<>
    struct completions<MyClass> {
        int c;
        int d;
        void func_completion() {
            c = 0;
            d = 0;
        }
    };
    
    template<typename CONFIG>
    struct Test : completions<CONFIG> {
        int a;
        int b;
    
        // functions
        void func() {
            a = 0;
            b = 0;
            this->func_completion();
        }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-18
      • 2016-02-13
      • 1970-01-01
      • 2013-10-13
      相关资源
      最近更新 更多