[英]What expressions yield a reference type when decltype is applied to them?
[英]Return type of decltype when applied to ternary(?:) expression
當我查看代碼片段以獲得std :: common_type的可能實現時
template <class ...T> struct common_type;
template <class T>
struct common_type<T> {
typedef decay_t<T> type;
};
template <class T, class U>
struct common_type<T, U> {
typedef decay_t<decltype(true ? declval<T>() : declval<U>())> type;
};
template <class T, class U, class... V>
struct common_type<T, U, V...> {
typedef common_type_t<common_type_t<T, U>, V...> type;
};
如何獲得兩個模板參數的通用類型的部分讓我感到困惑。它是使用decltype的三元運算符。
眾所周知,是否返回第二個或第三個操作數取決於第一個操作數的值。 在此片段中,第一個操作數為true ,這意味着expression的返回值將始終為declval<T>()
。 如果這是我認為沒有意義的...因此,我嘗試了以下測試
int iii = 2;
float fff = 3.3;
std::cout << typeid(decltype(false? std::move(iii):std::move(fff))).name() << std::endl;
std::cout << typeid(decltype(std::move(iii))).name() << std::endl;
std::cout << typeid(decltype(false ? iii : fff)).name() << std::endl;
std::cout << typeid(decltype(true ? iii : fff)).name() << std::endl;
// [02:23:37][ryu@C++_test]$ g++ -std=c++14 -g common_type.cpp
// output
// f
// i
// f
// f
與運行結果相比,結果我應該如下所示
int iii = 2;
float fff = 3.3;
std::cout << typeid(decltype(false ? iii : fff)).name() << std::endl; // should return f;
std::cout << typeid(decltype(true ? iii : fff)).name() << std::endl; // should return i;
任何人都可以幫助解釋為什么跑步結果不同?
換句話說,當它應用於三元表達式時,decltype的返回結果是什么?
表達式的類型是編譯時屬性。 條件表達式中的第一個操作數的值(以及因此選擇的分支)通常是運行時事物,因此它不可能影響表達式的類型。
相反,一組復雜的規則(超過一頁標准,我在這個答案中引用的大多數)用於確定第二個和第三個操作數的“常見類型”是什么,條件表達式是那種類型。 std::common_type
僅利用核心語言中的現有規則。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.