3

Possible Duplicate:
C++ invoke explicit template constructor

Hi,

template <typename T>
class testing
{
public:

    template <typename R>
    testing()
    {
       // constructor A
    }

    template <typename R>
    testing(const R&)
    {
       // constructor B
    }
};

What is the syntax to invoke the constructor A?

I will need the type to be passed during the constructor call. Is there a way to call it? constructor B is a workaround as I only need to know the type not the whole object.

Thanks,

Stephen

Community
  • 1
  • 1
stephenteh
  • 483
  • 1
  • 5
  • 8
  • sorry for the duplication, as I have no idea what to search for this one. Thanks for the reply below guys. – stephenteh Jul 03 '10 at 21:29
  • 1
    That's the issue with searching: when you don't know the term to qualify the problem, it's very hard to search for... – Matthieu M. Jul 04 '10 at 18:33

2 Answers2

3

you can create workaround:

template<class A>
testing(boost::mpl::identity<A>);

// and instantiate like this
testing(boost::mpl::identity<A>());

I asked very similar question before C++ invoke explicit template constructor

Community
  • 1
  • 1
Anycorn
  • 50,217
  • 42
  • 167
  • 261
2

You can't. The class template is based on the type T, so any template parameter you pass while instantiating the class will match T and not R.

Edit: You may also find this post useful: Constructor templates and explicit instantiation

You should go ahead with the workaround (constructor B). Most modern compilers will optimize out the unused parameter, so it should make no difference.

casablanca
  • 69,683
  • 7
  • 133
  • 150
  • 1
    Yes. the constructor A (constructor without argument) cannot be called. Although the compiler does not seem to give warning when it sees the class definition, there is just no way to call it. – rwong Jul 03 '10 at 20:55