bra*_*ing 6 c++ templates type-traits c++11
我想要一个类型特征 common
以便
common<int,int>::type -> int
common<const int, int>::type -> const int
common<int, int &>::type -> int
common<int &, int &>::type -> int &
common<int &, int const &>::type -> int const &
Run Code Online (Sandbox Code Playgroud)
那就是结果类型应该是两者中更受限制的.在C++ 11标准中是否有一个可以做到这一点的特性,还是我必须自己动手?
我的用例是我有类似的东西
template <typename T0, typename T1>
struct Foo {
BOOST_STATIC_ASSERT(
std::is_same
< typename std::decay<T0>::type
, typename std::decay<T1>::type
>::value
);
// I need to find T which is the most restrictive common
// type between T0 and T1
typedef typename common<T0,T1>::type T
T0 t0;
T1 t1;
T choose(bool c){
return c ? t0 : t1;
}
}
Run Code Online (Sandbox Code Playgroud)
恐怕你需要自己动手。您可以在 std::tuple 中扭曲您的类型,然后将其传递给std::common_type,例如
#include <tuple>
#include <type_traits>
template <class T1, class T2>
struct common {
using type = typename std::tuple_element<0, typename std::common_type<std::tuple<T1>, std::tuple<T2>>::type>::type;
};
template <class T>
struct common<const T, T> {
using type = const T;
};
template <class T>
struct common<T, const T> {
using type = const T;
};
template <class T>
struct common<const T, const T> {
using type = const T;
};
int main()
{
static_assert(std::is_same<common<int, int>::type, int>::value, "");
static_assert(std::is_same<common<const int, int>::type, const int>::value, "");
static_assert(std::is_same<common<int, int &>::type, int>::value, "");
static_assert(std::is_same<common<int &, int &>::type, int &>::value, "");
static_assert(std::is_same<common<int &, int const &>::type, int const &>::value, "");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但你必须为const.
| 归档时间: |
|
| 查看次数: |
182 次 |
| 最近记录: |