我不明白为什么这段代码编译没有错误:
#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;
}
按照标准是可以的,还是编译器容忍的?
最佳答案
draft C++11 standard 看起来有效,如果我们看一下5.2.3
部分显式类型转换(功能表示法)第2段说(强调我的 ):
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也是。
这在 constexpr 中没问题,即使第 7.1.5
段 3
说:
The definition of a constexpr function shall satisfy the following constraints:
并包括此项目符号:
its return type shall be a literal type;
and void 不是 C++11 中的 literal 根据 3.9
段落 10,但是如果我们再看第6段,它给出了一个适合这种情况的异常(exception),它说:
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.
作为凯西 noted在 C++14 draft standard void 是一个 literal,这是 3.9
部分 Types 段落 10 说:
A type is a literal type if it is:
包括:
— void; or
关于c++ - 回归虚无?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20478193/