問題描述
我不明白為什么這段代碼編譯沒有錯誤:
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:
并包括:
——無效;或
這篇關于回歸虛無?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!