Returning a void?(回归虚无?)
问题描述
我不明白为什么这段代码编译没有错误:
I do not understand why this code compiles without error:
#include <iostream>
template <class T>
struct Test
{
static constexpr T f() {return T();}
};
int main()
{
Test<void> test;
test.f(); // Why not an error?
return 0;
}
按照标准是可以的,还是编译器的容忍度?
Is it ok according to the standard, or is it a compiler tolerance?
推荐答案
这看起来有效 草案 C++11 标准,如果我们查看 5.2.3 部分 显式类型转换(功能符号)em> 段落 2 说(强调我的):
This looks valid by the draft C++11 standard, if we look at section 5.2.3 Explicit type conversion (functional notation) paragraph 2 says (emphasis mine):
表达式 T(),其中 T 是简单类型说明符或非数组完整对象类型的类型名称说明符 或(可能是 cv 限定的)void 类型,创建指定类型,其值是由值初始化产生的(8.5) 类型 T 的对象;void() 没有初始化案例.[...]
The expression T(), where T is a simple-type-specifier or typename-specifier for a non-array complete object type or the (possibly cv-qualified) void type, creates a prvalue of the specified type, whose value is that produced by value-initializing (8.5) an object of type T; no initialization is done for the void() case.[...]
措辞非常相似 pre C++11 也是如此.
the wording is pretty similar pre C++11 as well.
这在 constexpr 中没问题,尽管 7.1.5 段 3 说:
This okay in a constexpr even though section 7.1.5 paragraph 3 says:
constexpr 函数的定义应满足以下条件约束:
The definition of a constexpr function shall satisfy the following constraints:
并包括此项目符号:
它的返回类型应该是一个文字类型;
its return type shall be a literal type;
和 void 不是 C++11 中的 文字,如 3.9 部分 10,但是如果我们再看6段,它给出了一个适合这种情况的例外,它说:
and void is not a literal in C++11 as per section 3.9 paragraph 10, but if we then look at paragraph 6 it gives an exception that fits this case, it says:
如果一个 constexpr 函数的实例化模板特化类模板的模板或成员函数将无法满足constexpr 函数或 constexpr 构造函数的要求,该特化不是 constexpr 函数或 constexpr构造函数.[ 注意:如果函数是成员函数,它将仍然是常量,如下所述.—end note ] 如果没有专业化模板将产生一个 constexpr 函数或 constexpr构造函数,程序格式错误;无需诊断.
If the instantiated template specialization of a constexpr function template or member function of a class template would fail to satisfy the requirements for a constexpr function or constexpr constructor, that specialization is not a constexpr function or constexpr constructor. [ Note: If the function is a member function it will still be const as described below. —end note ] If no specialization of the template would yield a constexpr function or constexpr constructor, the program is ill-formed; no diagnostic required.
正如凯西在C++14 草案标准 void 是一个文字,这是 3.9 Types 段 10 说:
As Casey noted in the C++14 draft standard void is a literal, this is section 3.9 Types paragraph 10 says:
一个类型是文字类型,如果它是:
A type is a literal type if it is:
并包括:
——无效;或
这篇关于回归虚无?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:回归虚无?
基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
