【问题标题】:What is the correct syntax to call a enum class enumerators that are inside a templatized class?调用模板化类中的枚举类枚举器的正确语法是什么?
【发布时间】:2023-04-07 07:41:02
【问题描述】:

我不知道如何从模板化类访问枚举类枚举器,无论是作为返回值还是仅作为值。正如您在以下示例中看到的那样,我完全一无所知。我用谷歌搜索了错误消息,但没有运气。

很高兴您指出正确的语法。

首先这些是错误:

$ g++ -Wall -std=c++11 -o main.out main.cpp

main.cpp:25:1: 错误:在“C::Values”之前需要“typename”,因为“C”是一个依赖范围

C::Values C::Get() // 错误:'template class C' used without template parameters

C::Values 值; //

^

$

这是完整的示例,因此可以对其进行测试:

template<int Val>
class C
{
public:
    enum class Values{ one, two };

    C();
    Values Get();

private:
    int val;
};

template<int Val>
C<Val>::C() : val{ Val } {}

template<int Val>
C<Val>::Values C<Val>::Get() // <-- Error here ...
{
    return Values::one;
}

int main(void)
{
    C<5> aVariable;

    C::Values values; // <-- ... and here

    return 0;
}

感谢您的提前!!

【问题讨论】:

    标签: c++ class templates


    【解决方案1】:

    你需要帮助编译器告诉 Value 是 typename:

    template<int Val>
    typename C<Val>::Values C<Val>::Get() 
    

    在第二种情况下,您还需要提供模板参数,例如0:

    C<0>::Values values;
    

    您可以阅读此答案至Officially, what is typename for? 以获得更多解释。

    【讨论】:

    • 谢谢@Yola。您的解决方案按原样工作!我会尽快阅读您指出的文档,以找出为什么需要 typaneme 关键字和 占位符。
    【解决方案2】:

    首先,你需要使用关键字typename作为依赖类型名称C&lt;Val&gt;::Values,例如

    template<int Val>
    typename C<Val>::Values C<Val>::Get()
    ~~~~~~~~
    

    其次,您需要为类模板C指定模板参数,例如

    C<5>::Values values;
     ~~~
    

    LIVE

    看看Where and why do I have to put the “template” and “typename” keywords?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多