Search code examples
c++template-classes

template class instantiation in another class in c++


I have a template class that when I instantiate in main doesn't have any issues but when i try instantiating the same in another class is giving issues. can someone please enlighten me on the solution for this

#include<iostream>
#include<string>
using namespace std;

template <class T>
class property {
public:
    property(string name)
    {
        propertyName= name;
    }
private:
    T item;
    string propertyName;
};
main()
{
    property<int> myIntProperty("myIntProperty");
}

the above code compiles with out any issue. but

#include<iostream>
#include<string>
using namespace std;

template <class T>
class property {
public:
    property(string name)
    {
        propertyName= name;
    }
private:
    T item;
    string propertyName;
};

class propertyHolder
{
    property<int> myIntProperty("myIntProperty");
};

this code is not getting compiled. giving me error like

main.cpp|19|error: expected identifier before string constant| main.cpp|19|error: expected ',' or '...' before string constant|

Thanks, Harish


Solution

  • You wanted to declare field in class propertyHandler. That syntax is not working because you cannot declare a field and assing it value at the same spot.

    You can delcare it, and initialise in constructor:

    property<int> myIntProperty;
    
    propertyHolder(): myIntProperty("name") {}
    

    or with c++11 syntax:

    property<int> myIntProperty{"name"};
    

    or declare it static, and them declare like that:

    static property<int> myIntProperty;
    

    and after class declaration:

    property<int> propertyHolder::myIntProperty("name");