When I look into a code snippet for a possible implementation of 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;
};
The part how to get a common type for two template argument makes me confused.It is a usage of ternary operator with decltype.
As I known, whether to return the second or third operand is decided by the value of first operand. In this snippet, the first operand is true which means the return value of expression will always be declval<T>(). If it is what i thought which make no sense... Therefore, I have tried the following test
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
Comparing with the running result, The result what i though should be like as follows
int iii = 2;
float fff = 3.3;
std::cout << typeid(decltype(false ? iii : fff)).name() << std::endl; // should return i;
std::cout << typeid(decltype(true ? iii : fff)).name() << std::endl; // should return f;
Anyone when can help to explain why the running result is different ?
In other words, what's the return result of decltype when it is applied on a ternary expression?
Aucun commentaire:
Enregistrer un commentaire