且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C ++ 11方式编写模板以选择较大的整数类型?

更新时间:2023-11-30 22:23:58

你的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;