代码之家  ›  专栏  ›  技术社区  ›  KiraHoneybee

具有构造函数参数的模板化类

  •  1
  • KiraHoneybee  · 技术社区  · 2 年前

    考虑此类:

    template <typename t>
    class Something
    {
    public:
        Something(t theValue) {mValue=theValue;}
        t mValue;
    };
    

    当我这样做时,一切都很好:

    Something<float>* mSomething=new Something<float>(100);
    

    但是,如果我尝试这样做:

    Something<float> mSomething(100);
    

    我在另一个类中声明上述内容,即。

    class SomethingElse
    {
    public:
         Something<float> mSomething(100);
    };
    

    它告诉我,我放在括号内的任何东西都是语法错误。

    这里需要的语法到底是什么?或者这是模板的一些怪癖,因此不可能?

    此处的失败代码示例: https://wandbox.org/permlink/anaQz9uoWwV9HCW2

    1 回复  |  直到 2 年前
        1
  •  0
  •   Vlad from Moscow    2 年前

    不能将此类初始值设定项用作函数调用

    class SomethingElse
    {
    public:
         Something<float> mSomething(100);
    };
    

    您需要使用等号或括号内的初始值设定项。例如

    class SomethingElse
    {
    public:
         Something<float> mSomething { 100 };
    };
    

    这是一个演示程序。

    template <typename t>
    class Something
    {
    public:
        Something(t theValue) {mValue=theValue;}
        t mValue;
    };
    
    class SomethingElse
    {
    public:
         Something<float> mSomething{ 100 };
    };
    
    int main()
    {
    }
    

    根据C++语法

    member-declarator:
        declarator virt-specifier-seqopt pure-specifieropt
        declarator brace-or-equal-initializeropt
        identifieropt attribute-specifier-seqopt: constant-expression
    

    参见术语 大括号或同等初始值设定项 .