【问题标题】:c++ call specific template constructor of template classc++调用模板类的特定模板构造函数
【发布时间】:2011-09-15 11:45:17
【问题描述】:

如果类也是模板,是否可以使用模板参数调用构造函数?

#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;
}

编辑:所以我想调用特定模板构造函数的唯一方法是使用您想要的模板类型来调用它:

#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;
}

// 这个输出: 漂浮 双重

edit2:但是不属于构造函数参数本身的构造函数模板参数会发生什么?

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

【问题讨论】:

  • 请注意,您的构造函数应该能够推断您传递给他的参数的类型,而无需明确指定。
  • 您能在问题中添加一些标点符号吗?我不知道如何解析它!
  • this 的可能副本。请注意,作为模板的外部类是无关紧要的。
  • 我认为 edit2 值得提出他自己的问题。 stackoverflow.com/questions/6358882/…

标签: c++ templates constructor


【解决方案1】:

edit2:但是不属于构造函数参数本身的构造函数模板参数会发生什么?

然后你可以传入一个对其进行编码的参数

template<typename T> struct encodeType { };

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

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

【讨论】:

    【解决方案2】:
    Class<int> c(1.0f); //f in 1.0 makes it float type!
    Class<int>* ptr = new Class<int>(2.0f);
    

    这就够了。它将调用具有模板参数float 的构造函数。从参数1.0f,编译器将推导出构造函数模板的类型参数。因为1.0ffloat,所以编译器会推导出的类型参数是float

    同样见这些:

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

    【讨论】:

      【解决方案3】:

      您需要明确声明类本身的模板类型(在您的示例中为A)。但是你不需要说B 是什么类型。编译器从你传递1.0f 知道B == float。构造函数调用中没有任何内容可以帮助编译器找出A 是什么,所以你必须告诉它:

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

      【讨论】:

        【解决方案4】:

        在您给您的示例中,实际上不需要显式地提供template 参数来调用构造函数,例如:

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

        只需提供 1.0f 的参数就足够了:

        Class<int> c(1.0f);
        

        同样的事情也适用于new 示例。话虽如此,我认为您不能使用 template 参数显式调用构造函数(与普通函数不同)。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-05-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多