問題描述
我不明白為什么這段代碼編譯沒有錯(cuò)誤:
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;
}
按照標(biāo)準(zhǔn)是可以的,還是編譯器的容忍度?
Is it ok according to the standard, or is it a compiler tolerance?
推薦答案
這看起來有效 草案 C++11 標(biāo)準(zhǔn),如果我們查看 5.2.3
部分 顯式類型轉(zhuǎn)換(功能符號(hào))em> 段落 2 說(強(qiáng)調(diào)我的):
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):
表達(dá)式 T(),其中 T 是簡單類型說明符或非數(shù)組完整對(duì)象類型的類型名稱說明符 或(可能是 cv 限定的)void 類型,創(chuàng)建指定類型,其值是由值初始化產(chǎn)生的(8.5) 類型 T 的對(duì)象;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 函數(shù)的定義應(yīng)滿足以下條件約束:
The definition of a constexpr function shall satisfy the following constraints:
并包括此項(xiàng)目符號(hào):
它的返回類型應(yīng)該是一個(gè)文字類型;
its return type shall be a literal type;
和 void 不是 C++11 中的 文字,如 3.9
部分 10,但是如果我們?cè)倏?em>6段,它給出了一個(gè)適合這種情況的例外,它說:
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:
如果一個(gè) constexpr 函數(shù)的實(shí)例化模板特化類模板的模板或成員函數(shù)將無法滿足constexpr 函數(shù)或 constexpr 構(gòu)造函數(shù)的要求,該特化不是 constexpr 函數(shù)或 constexpr構(gòu)造函數(shù).[ 注意:如果函數(shù)是成員函數(shù),它將仍然是常量,如下所述.—end note ] 如果沒有專業(yè)化模板將產(chǎn)生一個(gè) constexpr 函數(shù)或 constexpr構(gòu)造函數(shù),程序格式錯(cuò)誤;無需診斷.
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 草案標(biāo)準(zhǔn) void 是一個(gè)文字,這是 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:
一個(gè)類型是文字類型,如果它是:
A type is a literal type if it is:
并包括:
——無效;或
這篇關(guān)于回歸虛無?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!