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:
并包括:
——无效;或
这篇关于回归虚无?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:回归虚无?
基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何通过C程序打开命令提示符Cmd 2022-12-09
