John Dibling
John Dibling

Reputation: 101456

Specializing Template Constructor Of Template Class

My brain has melted due to several weeks of 14-hour days.

I have a template class, and I'm trying to write a template convert constructor for this class, and specialize that constructor. The compiler (MSVC9) is quite displeased with me. This is a minimal example of actual code I'm trying to write. The compiler error is inline with the code.

Help me unmelt my brain. What's the syntax I need here to do what I'm trying to do? NOTE: In my real code, I must define the convert constructor outside of the declaration, so that's not an option for me.

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

template<typename A>
class Gizmo
{
public:
    Gizmo() : a_() {};
    Gizmo(const A& a) : a_(a) {};
    template<typename Conv> Gizmo(const Conv& conv) : a_(static_cast<A>(conv)) {};

private:
    A a_;
};

//
// ERROR HERE:
// " error C2039: 'Gizmo<B>' : is not a member of 'Gizmo<A>'"
//
template<> template<typename B> Gizmo<string>::Gizmo<typename B>(const B& b)
{
    stringstream ss;
    ss << b;
    ss >> a_;
}

int main()
{
    Gizmo<int> a_int;
    Gizmo<int> a_int2(123);
    Gizmo<string> a_f(546.0f);

    return 0;
}

Upvotes: 7

Views: 2321

Answers (1)

icecrime
icecrime

Reputation: 76755

template<> template<typename B> Gizmo<string>::Gizmo(const B& b)

Also note that the typename keyword from const typename B& must be removed.

Upvotes: 7

Related Questions