c++ - 在构造函数声明中写入模板类型的参数列表是否有效?

标签 c++ templates

旧 GCC 4.1.2 accepts , 和新的 GCC 4.5.1 accepts , 以下程序。

但这真的是正确的吗?对于像这样使用类型的模板参数声明构造函数,标准有何规定?

(我发现我不被允许 do the same in the out-of-line definition 很有趣。)

#include <iostream>
template <typename T>
struct Foo {
   Foo<T>(); // <---
};

template <typename T>
Foo<T>::Foo() {
  std::cout << ":)";
}

int main() {
   Foo<int> f;
}

我问的原因是它是在 this answer 的评论中提出的GCC 可能在这里出错。

最佳答案

我会把我最近在圣诞节寄出的可能的 DR 的邮件拷贝放在这里

Is the following code well formed?

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

The several compilers that I tested (clang, g++ and comeau conline) accept this. Indeed 12.1 does not forbid this (A<T> is a name of that class and is not a typedef-name), but 8.3p1 says

An unqualified-id occurring in a declarator-id shall be a simple identifier except for the declaration of some special functions (12.3, 12.4, 13.5) ...

A constructor is a special member function, but the list of cross references does not include 12.1. Does that mean that the above code is ill-formed? Or is this an accidental omission?

如果您在外联定义中执行相同操作,您将尝试将模板参数传递给构造函数。这是有效代码

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

template<> A::A<int>() { }

规范说,当在查看类的范围时(就像在 A::A 中)在限定名称中使用注入(inject)的类名,那么当名称查找接受函数/构造函数名称时,注入(inject)的类名引用将被翻译为解析为该类的构造函数(如果名称查找上下文仅接受类型,则名称将保留为注入(inject)的类名,并将表示类类型)。在A::A之后,名称查找完成并产生构造函数。 <int>然后只能被解析为模板参数列表。如果您的构造函数中没有模板,您的代码将无效。

关于c++ - 在构造函数声明中写入模板类型的参数列表是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8636094/

相关文章:

c++ - 第 933 行 : Char 34: runtime error: reference binding to null pointer of type 'struct value_type' (STL_vector. h) - Leet 代码螺旋

c++ - 访问模板基类函数指针类型

c++ - 具有编译时间常数的模板特化

c++ - 从长远来看,使用调试器和大量使用 C++ 模板是否不兼容?

javascript - ES6 JavaScript 模板文字——它们能做什么和不能做什么

c++ - stdafx.h 的目的

c++ - 使用索引 for 循环遍历 Unordered_map

C++:无法理解编译错误

c++ - 是否有帮助使用私有(private)结构的功能

使用外部函数的 C++ 模板