3

以下のコードで、すべての特殊化の間で common_fn() をどのように共有しますか ( Widget<A<T> >TWidget<B<T> >が何であっても)。

#include <cassert>

struct Afoo {};
struct Bfoo {};

template<typename T> struct A { typedef Afoo Foo; };
template<typename T> struct B { typedef Bfoo Foo; };

template<typename Type> struct Widget
{
    Widget() {}
    typename Type::Foo common_fn() { return Type::Foo(); }
    int uncommon_fn() { return 1; }
};

template<typename T> struct Widget<A<T> >
{
    Widget() {}
    int uncommon_fn() { return 2; }
};

int main()
{
    Widget<A<char> > WidgetAChar;
    assert( WidgetAChar.common_fn() == Afoo() ); // Error
    assert( WidgetAChar.uncommon_fn() == 2 );
}

私は以前、質問をその本質だと思うものに単純化しようとしましたが、部分的な専門化と特性の文脈で質問する必要があることがわかりました.

4

1 に答える 1

1

あなたが何を目指しているのか、特にuncommon_fnイラストと同じくらいシンプルなのか、それとももっとシンプルなのかは少し不明です。

とにかく、与えられたサンプルコードについて、考えてみてください…

#include <cassert>
#include <typeinfo>

struct Afoo {};
struct Bfoo {};

template< class T > struct A { typedef Afoo Foo; };
template< class T > struct B { typedef Bfoo Foo; };

template< class Type >
struct UncommonResult { enum { value = 1 }; };

template< class Type >
struct UncommonResult< A< Type > > { enum { value = 2 }; };

template< class Type >
struct Widget
{
    Widget() {}
    typename Type::Foo common_fn() { return Type::Foo(); }
    int uncommon_fn() { return UncommonResult< Type >::value; }
};

int main()
{
    Widget<A<char> > WidgetAChar;
    assert( typeid( WidgetAChar.common_fn() ) == typeid( Afoo ) ); // OK
    assert( WidgetAChar.uncommon_fn() == 2 );
}

より一般的なものを処理するためにこれを一般化するuncommon_fnことは難しくありません。

また、@iammilind が前の質問で示した継承のトリックを検討することもできます。実際にはもっと簡単かもしれません。ただし、「間違った」関数実装にアクセスする可能性が追加されます。

乾杯 & hth。

于 2011-08-19T05:18:33.283 に答える