简体   繁体   中英

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).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM