c++ - 模板构造函数怪异

标签 c++ templates constructor

<分区>

Possible Duplicate:
Can the template parameters of a constructor be explicitly specified?

跟进我之前的 question , (我在edit 2中发现了这种情况)

代码简单:

#include <iostream>

struct Printer
{
  Printer() { std::cout << "secret code" << std::endl; }
};

template <class A>
struct Class
{
  template <class B, class C>
  Class(B arg)
  {
      C c; /* the 'secret code' should come from here */
      std::cout << arg << std::endl;
  }

  Class(double arg) { std::cout << "double" << std::endl; }
  Class(float arg) { std::cout << "float" << std::endl; }

  /* this forbids the use of printer in the first parameter */
  Class(Printer printer) { throw std::exception(); /* here be dragons */ }
};

int main()
{
  Class<int> c(1.0f);
  Class<int>* ptr = new Class<int>((double)2.0f);
  return 0;
}

// Can anyone print 'secret code' while creating an object of type 'Class' ?

详解:对于模板构造函数,是否可以在实例化对象时指定一个不属于构造函数参数的模板参数?

我认为这值得单独提出一个问题。

最佳答案

不,这不可能。

没有可用于向构造函数模板提供显式模板参数的语法。您只能为整个类模板提供显式模板参数。

[temp.arg.explicit] 中的以下文本(2003 年措辞,14.8.1/5)涵盖了该场景。虽然该子句是非规范的,但它向我们说明,作为语法的固有限制,这是不可能的:

Note: because the explicit template argument list follows the function template name, and because conversion member function templates and constructor member function templates are called without using a function name, there is no way to provide an explicit template argument list for these function templates.

这在一定程度上是由于您从未实际自己显式调用构造函数这一事实。例如,当您编写 A() 时,您并没有像调用函数那样调用构造函数,即使它看起来好像是(“转换成员函数模板和构造函数成员函数模板是在不使用函数名”)。

关于c++ - 模板构造函数怪异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6358882/

相关文章:

C++ - 在派生类中静态初始化基类保护的成员变量

c++ - 将排序数组的元素分成最少数量的组,使得新数组的元素之间的差异小于或等于 1

c++ - boost:tcp 客户端的 readline

c++ - 使用外部模板 (C++11)

c++ - 为什么模板参数推导/替换失败?

java - 为什么 Java 编译器在构造函数实例化中会丢失对泛型类型的跟踪?

c++ - 使函数对于指针和引用具有通用性

c++ - 为什么 asm 中的这种差异对性能很重要(在未优化的 ptr++ 与++ptr 循环中)?

c++ - 我可以重载具有类型特征的函数吗?

java - 如何用一个泛型构造函数替换两个 Java 构造函数