0

C ++のメタプログラミング手法でちょっとしたスマートペアクラスを実装しようとしています。クラスにさまざまな型と定数を含めることができるようにしたい。以下のコードのように:

template <typename F, typename S>
struct Pair {
    typedef F first;
    typedef S second;
};

template <typename F, bool Cond>
struct Pair {
    typedef F first;
    static const bool second = Cond;
};

しかし、このコードは gcc 4.8.1 でコンパイル エラーを引き起こします。

error: template parameter ‘class S’
template <typename F, typename S>
                      ^
error: redeclared here as ‘bool Cond’

const テンプレート パラメータによって構造体をオーバーロードする方法はありますか?

4

1 に答える 1

2

このようなものがあなたのニーズに合いますか?

#include <type_traits>

template <typename F, typename S>
struct Pair {
    typedef F first;
    typedef S second;
};

template <typename F>
struct Pair<F, std::integral_constant<bool, true>> {
    typedef F first;
    static const bool second = false;
};

template <typename F>
struct Pair<F, std::integral_constant<bool, false>> {
    typedef F first;
    static const bool second = true;
};

Pair<int, std::true_type> t;
Pair<int, std::false_type> f;

またはより一般的な方法で:

template <typename F, typename T, T Val>
struct Pair<F, std::integral_constant<T, Val>> {
    typedef F first;
    static const T second = Val;
};

Pair<int, std::integral_constant<int,42>> p;
于 2013-10-20T17:09:43.873 に答える