在构造函数声明中写模板类型的参数列表是否有效? [英] Is it valid to write the template type's parameter list in a constructor declaration?

查看:280
本文介绍了在构造函数声明中写模板类型的参数列表是否有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

旧版GCC 4.1.2 接受,新版GCC 4.5.1 接受以下程序。

Old GCC 4.1.2 accepts, and new GCC 4.5.1 accepts, the following program.

但它是否正确?关于使用类型的模板参数声明一个构造函数这样的标准是什么?

But is it actually correct? What does the standard say about declaring a constructor with the type's template parameter like this?

(我觉得有趣的是,我不允许< =http://codepad.org/vyfV9RTn =nofollow>在外联定义中执行相同操作。)

(I find it interesting that I'm not allowed to 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;
}

我问的原因是, a href =http://stackoverflow.com/questions/8635981/c-undefined-constructor/8636007#8636007>此回答此GCC可能出现错误。

The reason I ask is that it was proposed in comments on this answer that GCC may be in error here.

推荐答案

我会在这里圣诞节发送一个可能的DR的邮件副本

I will put a mail copy of a possible DR I recently sent out on Christmas here

下面的代码是否形成?

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

我测试的几个编译器(clang,g ++和comeau conline)
接受这个。实际上,12.1不禁止( A 是该
类的名称,并且不是typedef名称),但是8.3p1说

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

在一个declarator-id中出现的非限定id应该是一个简单的
标识符,除了一些特殊函数的声明(12.3,
12.4 ,13.5)...

构造函数是一个特殊的成员函数,但cross
引用的列表不包括12.1。这是否意味着上面的代码
是错误的?或者这是一个意外的遗漏?

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?

如果你在外联定义中做同样的事情,你会尝试传递模板构造函数的参数。这是有效的代码

If you do the same in an out-of-line definition, you will try to pass template arguments to a constructor. This is valid code

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

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

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

The spec says that when the injected class name is used in a qualified name when looking into the scope of the class (just as in A::A), then when name lookup accepts function/constructor names, the injected class name reference will be translated to be resolved to the constructor(s) of that class (if the name lookup context only accepts types, then the name will remain the injected class name, and will denote the class type). After A::A, name lookup is complete and yields the constructor. The <int> can then only be parsed as a template argument list. If there is no template among your constructors, your code will be invalid.

这篇关于在构造函数声明中写模板类型的参数列表是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆