使用特征时避免部分模板特化中函数定义的重复

2024-02-10

如何在所有专业化之间共享 common_fn() (例如Widget<A<T> > and Widget<B<T> >,无论下面代码中的 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 );
}

我曾尝试过earlier https://stackoverflow.com/questions/7116610/avoiding-duplication-of-function-definitions-in-template-specializations将问题简化为我认为的本质,​​但事实证明有必要在部分专业化和特征的背景下提出它。


有点不清楚你的目标是什么,特别是是否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。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用特征时避免部分模板特化中函数定义的重复 的相关文章

随机推荐