返回空格? [英] Returning a void?
问题描述
我不明白为什么这段代码编译没有错误:
#include< iostream>
template< class T>
struct Test
{
static constexpr T f(){return T();}
};
int main()
{
Test< void>测试;
test.f(); //为什么不报错?
return 0;
}
根据标准是否正确, / p>
草案C ++ 11标准,如果我们看一下 表达式T(),其中T是非数组完整对象类型的简单类型说明符或 href =http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2005/n1804.pdf =nofollow> pre C ++ 11 以及。 / p> 即使 5.2.3
: >
typename-specifier <
(可能是cv限定的)void类型创建
指定类型的prvalue,其值是通过值初始化
(8.5)生成的类型对象T;没有为void()
case。[...]进行初始化。
7.1.5
段落<$ c $
constexpr函数的定义应满足以下
约束:
并包含此项目:
其返回类型应为文字类型;
和 void 不是< , 我们然后看看段落 6 它给出了适合这种情况的例外,它说:
constexpr函数的模板专门化
类模板的模板或成员函数将无法满足
constexpr函数或constexpr构造函数的要求
专业化不是constexpr函数或constexpr
构造函数。 [注意:如果函数是一个成员函数,它将
仍然是const,如下所述。 -end note] 如果没有特殊化的
模板将产生一个constexpr函数或constexpr
构造函数,程序是不成形的;无需诊断。
As Casey 在 C中注明 ++ 14草案标准 void 是一个字符,这是 3.9
/ em>段落 10 说:
一个类型是文字类型,
并包括:
<或
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?
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):
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.[...]
the wording is pretty similar pre C++11 as well.
This okay in a constexpr even though section 7.1.5
paragraph 3
says:
The definition of a constexpr function shall satisfy the following constraints:
and includes this bullet:
its return type shall be a literal type;
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:
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.
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:
and includes:
— void; or
这篇关于返回空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!