Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ call specific template constructor of template class

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 */ }
like image 529
costy.petrisor Avatar asked Jun 15 '11 12:06

costy.petrisor


1 Answers

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).

like image 155
iammilind Avatar answered Sep 28 '22 14:09

iammilind