0

カスタムメソッドが必要です-テンプレート化されたクラスでMyMethodを呼び出します-Fooを呼び出します-Fooが特定のテンプレートパラメータータイプでインスタンス化されている場合のみ(たとえば、AがintでBがstringの場合)、それ以外の場合は、他の可能な Foo インスタンスに MyMethod がまったく存在しないようにします。

それは可能ですか?

例:

template<class A, class B>
class Foo
{
    string MyMethod(whatever...);
}

boost:enable_if はそこに役立ちますか?

ありがとう!!

4

1 に答える 1

0

ここで本当に必要なのは、テンプレートを特殊化することです。あなたの例では、次のように記述します。

template<>
class Foo<int, string>
{
    string MyMethod(whatever...); 
};

enable_if も使用できます。

template<typename A, typename B>
class Foo
{
    typename boost::enable_if<
            boost::mpl::and_<
                boost::mpl::is_same<A, int>,
                boost::mpl::is_same<B, string>
            >,
            string>::type MyMethod(whatever...){}
};

オーバーロードがない場合は、static_assert も使用できます。

template<typename A, typename B>
class Foo
{
    string MyMethod(whatever...)
    {
         static_assert(your condition here, "must validate condition");
         // method implementation follows
    }
};

これにより、条件が設定されていない状態で MyMethod を呼び出そうとすると、コンパイル エラーが発生します。

于 2012-06-28T10:36:20.730 に答える