scs-erin
scs-erin

Reputation: 75

How can I specialise a template function designed to return different types?

I currently have a function template that reads a string obtained from a configuration file and creates and returns a shared pointer to a new instance of a derived class:

template <typename T> std::shared_ptr<T> foo(std::string& info)
{ /* */ }

I would like to specialise this when I return a particular class, because it needs to handle the string differently, but I can't find a way of doing it. Trying

std::shared_ptr<Derived> foo(std::string& info)
{/* */}

and

template <> std::shared_ptr<Derived> foo(std::string& info)
{/* */}

both fail because I appear to be breaking the one definition rule. I've also tried

template <> std::shared_ptr<Derived> foo<std::shared_ptr<Derived>>(std::string& info)
{/* */}

but I received Visual Studio error message C2192 (explicit specialization 'declaration' is not a specialization of a function template).

Upvotes: 2

Views: 50

Answers (1)

Fran&#231;ois Andrieux
Fran&#231;ois Andrieux

Reputation: 29072

You just need to supply the template argument after the identifier. Your last attempt was close but the template argument is Derived not std::shared_ptr<Derived> :

template <> std::shared_ptr<Derived> foo<Derived>(std::string& info)
//        Add the template argument here ^^^^^^^

Simplified example : https://godbolt.org/z/aoczzj

Upvotes: 2

Related Questions