c++classtemplatesparametersconstructor

Templated class with constructor arguments


Consider this class:

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

When I do this, everything is okay:

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

HOWEVER, if I try to do this:

Something<float> mSomething(100);

I am declaring the above inside another class-- i.e.

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

It tells me that anything I put inside the parenthesis is a syntax error.

What exactly is the necessary syntax here-- or is this some quirk of templates and thus not possible?

Fail code example here: https://wandbox.org/permlink/anaQz9uoWwV9HCW2


Solution

  • You may not use such an initializer as a function call

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

    You need to use an equal or braced initializer. For example

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

    Here is a demonstration program.

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

    According to the C++ grammar

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

    See the term brace-or-equal-initializer.