当使用trait时,避免在部分模板特化中重复函数定义

Avoiding duplication of function definitions in partial template specializations when using traits

本文关键字:定义 函数 trait      更新时间:2023-10-16

如何在下面的代码中在所有专门化(对于Widget<A<T> >Widget<B<T> >,无论T是什么)之间共享common_fn() ?

#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 );
}

我早先曾试图把这个问题简化成我认为是它的本质,但事实证明,有必要在部分专业化和特征的背景下提出这个问题。

这有点不清楚你的目标是什么,特别是uncommon_fn是否真的像所示的那样简单,或者可能更多。

但是无论如何,对于给出的示例代码,考虑& help;

#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 .