11

2 つのテンプレート パラメーターを受け取るテンプレート関数の 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 の新しい機能を利用できますか? 可変個引数テンプレートを使用して、型のペアだけでなく、pick_first を使用する代わりに、新しい int_leastX_t および int_fastX_t 型で動作するように多くの特殊化を記述できることを知っています。しかし、これに対する単純なより良いアプローチがあるかどうか、私は興味があります。多分どういうわけかauto/constexpr/decltypeを活用していますか?

4

3 に答える 3

11

あなたのpick_firstはC++11ではstd::conditionalなので、次のように書くことができます。

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.
};

両方の型を含む式の結果を保持するのに適した型が必要で、必ずしも2つの型のいずれかを正確に必要としない場合はstd::common_type、またはおそらくautoが最善の解決策です。

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の実装には、次のものがありませんtypenametypedef typename pick_first<(sizeof(T) >= sizeof(U)), T, U>::type type;

于 2012-09-25T05:09:45.537 に答える
2

どちらのタイプも署名されていないため、そのまま実行してくださいdecltype( T1() + T2() )

于 2012-09-25T04:19:50.903 に答える