模板构造函数的怪异

Template constructor weirdness

本文关键字:构造函数      更新时间:2023-10-16

可能重复:
构造函数的模板参数可以显式指定吗?

继我之前的问题之后,(我在编辑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)涵盖了该场景。尽管该条款是非规范性的,但它可以向我们解释,作为语法的固有限制,这是不可能的:

注意:因为显式模板函数后面的参数列表模板名称,以及,因为转换成员函数模板和构造函数成员函数模板在不使用函数的情况下调用name无法提供的显式模板参数列表这些函数模板

这在一定程度上源于这样一个事实,即您从未亲自显式调用构造函数。例如,当您编写A()时,您并不是像函数一样调用构造函数,即使它看起来像是("在不使用函数名的情况下调用转换成员函数模板和构造函数成员函数模板")。

我想他想知道如何用C将这个类实例化为SomeType:

template<typename A>
class foo
{
    template<typename B, typename C>
    foo(B b)
    {
        C c;
    }
};

我不知道这是否可能。