c++ call specific template constructor of template class

柔情痞子 提交于 2019-12-10 15:08:00

问题


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 */ }

回答1:


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

Then you can pass-in an argument that has it encoded

template<typename T> struct encodeType { };

struct A {
  template<typename T, typename U>
  A(T t, encodeType<U>) { }
};

A a(1, encodeType<float>());



回答2:


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




回答3:


You need to explicitly state the template type that goes with the class itself (that's A in your example). But you don't need to say what type B is. The compiler knows from you passing 1.0f that B == float. There's nothing in the constructor call to help the compiler figure out what A is, so you have to tell it:

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



回答4:


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

This is enough. It will invoke the constructor which has template argument float. From the argument 1.0f, the compiler will deduce the type argument of the constructor template. Since 1.0f is float, so the type argument the compiler will deduce is float.

Likewise see these:

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


来源:https://stackoverflow.com/questions/6357394/c-call-specific-template-constructor-of-template-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!