Is it possible to call a constructor with template arguments if the class is a template too?
#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 guess the only way to call a specific template constructor is to call it with casted paramterers to the template type you want:
#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;
}
// this outputs: float double
edit2: but what happens to constructor template arguments that are not part of the constructor arguments itself ?
template <class B, class C>
Class(B arg) { /* how do you specify ?? C */ }
In the example you gave you actually don't need to explicitly give the template
argument to invoke constructor like:
Class<int> c<float>(1.0f);
Simply providing argument as 1.0f
is enough:
Class<int> c(1.0f);
Same thing is applicable for new
example too. Having said that, I don't think constructor you can invoke explicitly using template
argument (unlike normal function).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With