33

次のコードを検討してください。

template<bool AddMembers> class MyClass
{
    public:
        void myFunction();
        template<class = typename std::enable_if<AddMembers>::type> void addedFunction();

    protected:
        double myVariable;
        /* SOMETHING */ addedVariable;
};

このコードでは、テンプレート パラメーターAddMembersを使用して、クラスに関数を追加できますtrue。そのために、 を使用しstd::enable_ifます。

私の質問は次のとおりです:データメンバー変数に対して同じことが可能ですか(おそらくトリックを使用)? MyClass<false>( 1 つのデータ メンバー ( myVariable) とMyClass<true>2 つのデータ メンバー (myVariableおよび) を持つような方法でaddedVariable?

4

2 に答える 2

34

条件付き基本クラスを使用できます。

struct BaseWithVariable    { int addedVariable; };
struct BaseWithoutVariable { };

template <bool AddMembers> class MyClass
    : std::conditional<AddMembers, BaseWithVariable, BaseWithoutVariable>::type
{
    // etc.
};
于 2012-08-24T23:38:06.607 に答える
30

まず、あなたのコードはMyClass<false>. このenable_if特性は、クラス テンプレートの引数ではなく、推定された引数に役立ちます。

次に、メンバーを制御する方法は次のとおりです。

template <bool> struct Members { };

template <> struct Members<true> { int x; };

template <bool B> struct Foo : Members<B>
{
    double y;
};
于 2012-08-24T23:40:52.080 に答える