[英]conditional declaration of type using decltype
我認為條件類型可以在模板函數中使用decltype
聲明。 但似乎沒有。 誰能指出我的測試代碼有什么問題?
#include <boost/type_index.hpp>
using boost::typeindex::type_id_with_cvr;
#define print_type(var) do { \
std::cout << type_id_with_cvr<decltype(var)>().pretty_name() << std::endl; \
} while(0)
template <typename T1, typename T2>
auto max(T1 a, T2 b) -> decltype(a < b ? b : a) {
decltype(a < b ? b : a) c = a < b ? b : a;
print_type(c);
return a < b ? b : a;
}
int main() {
int i = 10;
double d = 3.3;
decltype(i < d? d : i) r = i < d? d : i;
print_type(r); // -> double
std::cout << r << std::endl; // 10
}
我想你的意圖
decltype( a < b ? a : b )
是獲得的類型b
當a < b
和類型a
否則。
那就是:我想你的意圖是根據a
和b
的欠幅時間值獲得一個確定類型的運行時間 。
這在C ++中是不可能的,因為變量的類型必須由編譯時決定。
使用該decltype()
您將獲得三元運算符的類型
a < b ? a : b
這不取決於a
和b
的值,而只取決於它們的類型。
所以,在這種情況下
decltype(i < d? d : i)
其中i
是int
, d
是double
,你得到一個double
, i
和d
的值是無關緊要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.