C ++ template constructor specific template class templates

Is it possible to call a constructor with template arguments if the class is also a template?

#include <stdio.h> #include <iostream> template <class A> struct Class { template <class B> Class(B arg) { std::cout << arg << std::endl; } }; int main() { Class<int> c<float>(1.0f); Class<int>* ptr = new Class<int><float>(2.0f); return 0; } 

edit: so I assume that the only way to invoke a specific template constructor is to invoke it using casted paramterers on the desired template type:

 #include <stdio.h> #include <iostream> template <class A> struct Class { template <class B> Class(B arg) { std::cout << arg << std::endl; } Class(double arg) { std::cout << "double" << std::endl; } Class(float arg) { std::cout << "float" << std::endl; } }; int main() { Class<int> c(1.0f); Class<int>* ptr = new Class<int>((double)2.0f); return 0; } 

// these outputs: double float

edit2: but what happens to the design arguments of the template that are not part of the constructor arguments themselves?

 template <class B, class C> Class(B arg) { /* how do you specify ?? C */ } 
+4
source share
4 answers

edit2: but what happens to the design arguments of the template that are not part of the constructor arguments themselves?

Then you can pass the argument that encoded

 template<typename T> struct encodeType { }; struct A { template<typename T, typename U> A(T t, encodeType<U>) { } }; A a(1, encodeType<float>()); 
+2
source

In the example that you actually gave you , you do not need to explicitly specify the template argument to invoke a type constructor:

 Class<int> c<float>(1.0f); 

Just providing an argument as 1.0f enough:

 Class<int> c(1.0f); 

The same applies for the new example. Having said that, I do not think that you can explicitly call the constructor using the template argument (as opposed to the normal function).

+4
source
 Class<int> c(1.0f); //f in 1.0 makes it float type! Class<int>* ptr = new Class<int>(2.0f); 

It's enough. It will call the constructor with the float template argument. From the argument 1.0f compiler will 1.0f argument of the type of the constructor template. Since 1.0f is a float , the type argument to be issued by the compiler is float .

Similarly, see the following:

 Class<int> c(1.0); //this will invoke Class<int><double>(double); Class<int>* ptr = new Class<int>(2); //this will invoke Class<int><int>(int); 
+1
source

You need to explicitly specify the type of template that comes with the class itself (this is A in your example). But you do not need to say what type B The compiler knows that you pass 1.0f , which is B == float . There is nothing in the constructor call to help the compiler figure out what A , so you should tell it:

 Class<int> c(1.0f); Class<int>* ptr = new Class<int>(2.0f); 
+1
source

All Articles