【问题标题】:Templated enum types based on template parameters基于模板参数的模板化枚举类型
【发布时间】:2013-08-12 07:26:10
【问题描述】:

我想知道如何做到这一点: 假设我有一个 A 类,里面有枚举 B

class A {

enum B {

};

};

我想创建一个以 A 作为模板的函数,然后假设 A 具有枚举 B 类型并接收其 val 作为参数?我试过类似的东西:

template<typename T>
static void Foo(T t, T::B b) {}

但这不起作用..有人有想法吗?

谢谢。

【问题讨论】:

  • 您是否必须确保T 扩展A
  • 不,假设枚举存在
  • 使用 A::B 不是更正确吗?
  • @user2672165 这是一个模板。 (见:template&lt;typename T&gt;
  • @Rapptz:你是对的。我应该至少读两遍问题。

标签: c++ templates enums


【解决方案1】:

您需要告诉编译器T::B 是一个类型,因为它是一个依赖名称,并且默认假定为非类型。

template<typename T>
static void Foo(T t, typename T::B b) {}
//                   ^^^^^^^^

您还应该公开枚举。此代码示例有效:

class A {
 public:
  enum B {x, y, z};
};

template<typename T>
static void Foo(T t, typename T::B b) {}

int main()
{
  Foo(A(), A::x); // OK
}

更深入的解释见Where and why do I have to put the “template” and “typename” keywords?

【讨论】:

    【解决方案2】:

    您必须使用 typename 关键字才能使其工作:

    static void Foo(T t, typename T::B b) {}
                            ^
    

    并且enum B 必须是公开的。

    typename 关键字它用于指定模板定义或声明中的依赖名称是一种类型。它是模板参数中class 的同义词。

    C++ 标准状态:

    模板声明或定义中使用的名称,即 假定依赖于模板参数不命名类型,除非 适用的名称查找找到一个类型名称或该名称是合格的 通过关键字类型名。

    因此,除非您明确声明 typename T::B b,否则编译器将假定 T::B b 是值类型而不是类型名称。

    总结一下:

    class A {
     public:
      enum B {enum1, enum2};
    };
    
    template<typename T>
    static void Foo(T t, typename T::B b) {}
    
    int main()
    {
      A a;
      Foo(a, a::enum1); 
    }
    

    typename

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多