Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 280
John Dibling Avatar asked Nov 11 '10 20:11

John Dibling


People also ask

What is meant by template specialization?

The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.

Can you template a constructor?

As long as you are satisfied with automatic type inference, you can use a template constructor (of a non-template class). @updogliu: Absolutely. But, the question is asking about "a template constructor with no arguments" If there are no function arguments, no template arguments may be deduced.

What is class template and template class in C++?

An individual class defines how a group of objects can be constructed, while a class template defines how a group of classes can be generated. Note the distinction between the terms class template and template class: Class template. is a template used to generate template classes.

What does template <> mean in C++?

Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one.


1 Answers

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

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

like image 74
icecrime Avatar answered Sep 22 '22 07:09

icecrime