c++ - 模板化类构造函数的模板实例化

标签 c++ templates clang++

这无法用 clang++ 编译,有人可以解释为什么吗? (这用 g++ 编译得很好)

struct X
{
  template <typename T> X() {}
};

template X::X<int>();

int main() { return 1; }



instantiate.cc:7:13: error: qualified reference to 'X' is a constructor name rather than a type in this context
template X::X<int>();
            ^
instantiate.cc:7:14: error: expected unqualified-id
template X::X<int>();
             ^
2 errors generated.

最佳答案

构造函数没有名字。正如 [class.ctor]/1 所说的那样。它们是使用类名定义的特殊成员。但他们自己是无名的。虽然 C++ 允许我们通过使用类名在某些上下文中引用 c'tor,但这些是有限的。通常,我们不能命名 c'tor。
这就是问题所在。要明确指定模板参数,我们必须使用模板化实体的名称。构造函数没有名称,因此我们无法明确指定它们的参数。
这是 [temp.arg.explicit] 中一个注释的主题,它总结了规范文本的意图。

7 [ 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.  — end note ]


我们仍然可以实例化或特化构造函数,但前提是不必显式指定模板参数(如果它们是可推导的,或者来自默认模板参数)。例如
struct X
{
  template <typename T> X(T) {}
};

template X::X(int); // This will work
所以 Clang 拒绝你的代码并没有错。并且 GCC 有可能提供扩展。但最终,该标准没有提供一种向构造函数模板显式提供模板参数的方法。

进一步挖掘后,有 CWG581 ,进一步确认 Clang 的行为是预期的。它似乎也进入了最新的标准修订版,并对规范文本进行了一些更改。

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

相关文章:

c# - 有没有办法从非 Web 应用程序处理 MVC View (aspx 文件)?

c++ - 在 libc++ 的 istringstream 的析构函数中未定义对运算符 delete 的引用

c++ - mysql 连接器/C++ 手册

C++,将n个参数的函数作为参数传递

c# - 通过 Net Core 将 C++ 数组传递到 C# 层

templates - D:显示给定类型是否具有可比性的模板约束

c++ - -std=c++ 98 和 OS X 10.10

c++ - 地址 sanitizer 失败

c++ - 二进制文件处理程序未写入最后一个值

C++ strftime() 不正确的输出