使用特征时,避免在部分模板专业化中重复定义功能 [英] Avoiding duplication of function definitions in partial template specializations when using traits

查看:106
本文介绍了使用特征时,避免在部分模板专业化中重复定义功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How does one share common_fn() among all specializations (for Widget<A<T> > and Widget<B<T> >, no matter what T is) in the code below?

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

我曾尝试较早地将问题简化为我以为是它的本质,但事实证明,有必要在部分专业化和特质的背景下提出它.

I had tried earlier to simplify the question to what I thought was its essence, but it turns out that it is necessary to ask it in the context of partial specialization and traits.

推荐答案

目前尚不清楚您的目标是什么,尤其是uncommon_fn是否真的如插图所示那样简单,或者可能更多.

It's a little unclear what you're aiming for, in particular whether uncommon_fn is really as simple as illustrated, or might be more.

但是无论如何,对于给出的示例代码,请考虑…

But anyway, for the example code given, consider …

#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并不难.

Generalizing this to handle a more general uncommon_fn shouldn't be hard.

您还可以考虑@iammilind为您上一个问题显示的继承技巧.实际上可能更简单.但是,它增加了访问可能错误"的函数实现的可能性.

You might also consider the inheritance trick that @iammilind showed for your previous question. It might be practically simpler. However, it adds the possibility of accessing a possibly "wrong" function implementation.

干杯hth.

这篇关于使用特征时,避免在部分模板专业化中重复定义功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆