C ++ 11方式编写模板以选择较大的整数类型? [英] C++11 way to write template for picking bigger integer type?
问题描述
在C ++ 11中的编译时,在一个模板函数中,它需要2个模板参数,两个都必须是无符号整数类型,我想有一个局部变量有两个模板参数的类型更多位。在C ++ 03中,我可以写如下:
At compile time in C++11 in a template function that takes 2 template parameters, both of which must be unsigned integer types, I'd like to have a local variable have the type of whichever of the two template parameters has more bits. In C++03 I might write something like:
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功能,使这更简单?我知道我可以使用可变参数模板,使它不只是成对的类型,而不是使用pick_first我可以编写大量的专业化,使其工作与新的int_leastX_t和int_fastX_t类型。但我很好奇,如果只有一个更好的方法来解决这个问题。也许以某种方式利用auto / constexpr / decltype?
Can I leverage any of the new C++11 features to make this simpler? I know I could use variadic templates to make it work with more than just pairs of types, and instead of using pick_first I could write lots of specializations to make it work with the new int_leastX_t and int_fastX_t types. But I'm curious if there's just a plain better approach to this. Maybe somehow leveraging auto/constexpr/decltype?
推荐答案
你的pick_first只是std :: conditional在C ++ 11,可以写
Your pick_first is just std::conditional in C++11, so you could write
template<class T, class U>
struct wider {
using type = typename std::conditional<sizeof(T) >= sizeof(U), T, U>::type; // I'm using the C++11 type alias feature 1) to educate people about them and 2) because I like them better than typedefs.
};
如果你只想要一个类型适合保存一些涉及两种类型的表达式的结果,必须需要两个类型中的一个,然后 std :: common_type
或者也许 auto
是最好的解决方案: / p>
If you just want a type suitable for holding the result of some expression involving both types and don't necessarily need exactly one of the two types then std::common_type
, or perhaps auto
, is the best solution:
template<class uintX_t, class uintY_t>
void foo() {
typename std::common_type<uintX_t, uintY_t>::type mylocal = 0;
// insert doing stuff with mylocal here
}
// or
template<class uintX_t, class uintY_t>
void foo(uintX_t x, uintY_t y) {
auto mylocal = x + y;
}
且您的实现pick_bigger缺少 typename > c>
and your implementation of pick_bigger is missing a typename
in there: typedef typename pick_first<(sizeof(T) >= sizeof(U)), T, U>::type type;
这篇关于C ++ 11方式编写模板以选择较大的整数类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!