Michael
Michael

Reputation: 712

C++ template specialization with templated parameter

I try to write a templated class called Null as below;

template <class Type>
class Null;

template <>
class Null<std::string> {
  public:
    Null() {}
    operator std::string() const {
        return std::string();
    }
};

so far works good for string

but I want to write something like

template<> class Null<boost::shared_ptr<T>>
{
public:
    NUll(){}
    operator boost::shared_ptr<T>() const
    {
        return boost::shared_ptr<T>();
    }
};

But it won't compile, I tested other ways and couldn't work it out. How can I do this right?

Upvotes: 0

Views: 94

Answers (1)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153792

When your specialization needs a template parameter (or parameters) you better mention them:

template <typename T>
class Null<boost::shared_ptr<T>>
{
    // ...
};

Note that the list of template parameters in the primary type and in the specialization don't have any relationship! In particular, you can have many template arguments for a specialization. The canonical example is std::function<...>:

template <typename> class function; // primary template
template <typename RC, typename... Args>
class function<RC(Args...)> {
    // definition
};

In the case of std::function<...> the primary is even never defined!

Upvotes: 6

Related Questions