当使用trait时,避免在部分模板特化中重复函数定义
Avoiding duplication of function definitions in partial template specializations when using traits
如何在下面的代码中在所有专门化(对于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 .
相关文章:
- 在命名空间中定义函数还是限定函数
- 为什么在定义函数之前先声明它
- 使用用户定义函数的字符串反转
- 用户定义函数中的指针和输入
- 这个c++代码是如何在没有定义函数的情况下运行的
- 具有外部"c"和程序集的未定义函数
- 已定义函数时出现 G++ "未定义的引用"错误
- 将自定义函数传递到基抽象类中以延迟执行
- C++使用 rand 定义函数语法
- Arduino:在 loop() 和自定义函数中运行相同的代码时出现问题
- 将具有固定签名的自定义函数名称注入 CRTP
- 使用定义函数模板别名
- 是否可以使用单个定义定义函数的常量和常规版本?(使用模板,自动,decltype等)
- 在内联程序集中定义函数和从 C++ 调用时出现问题
- 在 Metal 着色器代码中,如何定义函数的 in/out 参数变量?
- 声明和定义函数静态会产生"undefined reference to function_name()"
- 朋友定义函数的名称空间是什么
- 介子 对用户定义函数的未定义引用
- 如何使用 "using" 关键字定义函数原型/签名
- 在 C 结构中定义C++函数