【发布时间】:2012-09-16 13:18:08
【问题描述】:
在 C++11 中编译时,在一个模板函数中,它接受 2 个模板参数,这两个模板参数都必须是无符号整数类型,我希望有一个局部变量具有两个模板参数中的任何一个的类型更多位。在 C++03 中,我可能会写如下内容:
template<bool, class T, class U>
struct pick_first;
template<class T, class U>
struct pick_first<true, T, U> {
typedef T type;
};
template<class T, class U>
struct pick_first<false, T, U> {
typedef U type;
};
template<class T, class U>
struct pick_bigger {
typedef typename pick_first<(sizeof(T) >= sizeof(U)), T, U>::type type;
};
// usage
template<class uintX_t, class uintY_t>
void foo() {
typename pick_bigger<uintX_t, uintY_t>::type mylocal = 0;
// insert doing stuff with mylocal here
}
我可以利用任何新的 C++11 功能来简化此操作吗?我知道我可以使用可变参数模板使其不仅仅适用于成对的类型,而且我可以编写许多专门化来使其适用于新的 int_leastX_t 和 int_fastX_t 类型,而不是使用 pick_first。但我很好奇是否有一个更好的方法来解决这个问题。也许以某种方式利用 auto/constexpr/decltype?
【问题讨论】:
-
你考虑过
std::common_type -
我没有听说过 std::common_type!很有意思。这对我有用。不过,您应该将其发布为答案,以便我投票给您;)
-
@DavidRodríguez-dribeas 但由于整数提升规则,
common_type并不总是有效。例如,std::common_type<short,char>::type是int,它可能大于这两种类型中的任何一种。 -
pick_first模板的名称似乎很恰当。 -
@Cheersandhth.-Alf:糟糕,已修复。
标签: c++ templates c++11 metaprogramming