Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do you call this template constructor? [duplicate]

Tags:

c++

templates

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

like image 343
stephenteh Avatar asked Jul 30 '26 23:07

stephenteh


2 Answers

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

like image 190
Anycorn Avatar answered Aug 01 '26 11:08

Anycorn


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.

like image 35
casablanca Avatar answered Aug 01 '26 11:08

casablanca



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!