nabber
nabber

Reputation: 59

boost::make_shared() with templated class?

I have seen there are a lot of questions/answers regarding usage of boost's make_shared() and templated classes, but being quite new at C++ I don't seem to find what I am looking for. So basically I have created a Class called Generic, which its manager class called GenericManager has the following public member.

class GenericManager
{
public:
typedef boost::shared_ptr<GeneriClass> GenericClassPtr;
//... more members etc
};

Now I have another class that's templated and I want to create a make_shared call, ie:

template <class MyType>
SpecificClass<MyType>::...
{
//class members functions etc
};

and then the call I want to do is:

GenericClassPtr SpecificClassFactory::construct()
{
    return boost::make_shared<SpecificClass>();
}

Which works fine for non templated version of SpecificClass but for the templated version I get the usual error:

error: no matching function for call to ‘make_shared()’ 

How could the make_shared called be alternated to accept the template type? For now I try to stick to C++98!

Edit: @wasthishelpful Fixed typo mentioned, thanks.

Upvotes: 2

Views: 1941

Answers (1)

rocambille
rocambille

Reputation: 15976

SpecificClass needs a template parameter:

return boost::make_shared<SpecificClass<SomeType> >();
// in C++98, do not forget space here           ^^^ 

So your construct method should have one as well, either for the whole class:

template<typename SomeType>
struct SpecificClassFactory
{
    static GenericClassPtr construct()
    {
        return boost::make_shared<SpecificClass<SomeType> >();
    }
};

// usage

GenericManager::GenericClassPtr ptr = SpecificClassFactory<SomeType>::construct();

Or only for the method:

template<typename SomeType>
GenericClassPtr SpecificClassFactory::construct()
{
    return boost::make_shared<SpecificClass<SomeType> >();
}

// usage

GenericManager::GenericClassPtr ptr = SpecificClassFactory::construct<SomeType>();

Note that your typedef in GenericClass may be better outside class declaration (see Zen of Python: "Flat is better than nested"):

class GenericManager
{
public:
//... more members etc
};

typedef boost::shared_ptr<GeneriClass> GenericClassPtr;

This will allow to call GenericClassPtr directly, instead of GenericManager::GenericClassPtr.

Upvotes: 3

Related Questions