Cal*_*laf 10 c++ templates partial-specialization
类Widget具有一些适用于所有参数类型(公共函数)的函数以及需要专用于给定类型的其他函数(非常见函数).
g ++坚持认为Widget的专业化也应该定义common_fn()而不仅仅是uncommon_fn(),但这首先会破坏使用特化的目的.如何避免重复common_fn()?
#include <cassert>
template<typename Type> struct Widget
{
Widget() {}
char common_fn() { return 'a'; }
int uncommon_fn() { return 1; }
};
template<> struct Widget<char>
{
Widget() {}
int uncommon_fn() { return 2; }
};
int main()
{
Widget<char> WidgetChar;
assert( WidgetChar.common_fn() == 'a' ); // Error
assert( WidgetChar.uncommon_fn() == 2 );
}
Run Code Online (Sandbox Code Playgroud)
开始编辑
对Alf:
我无法使用
template<> int Widget<char>::uncommon_fn() { return 2; }
Run Code Online (Sandbox Code Playgroud)
因为一些不常见的函数需要返回一个特征类型(因此通过制作实际的类型原语来简化它).
或者实际上有一种方法可以使编译器typename Foo::Bar在写入时识别
struct Foo { typedef FooBar Bar; };
template<> typename Foo::Bar Widget<Foo>::uncommon_fn() { return ....; }
Run Code Online (Sandbox Code Playgroud)
?
最终编辑
开始,EDIT2
致iammilind:
这很有趣,但出于同样的原因,我无法使用Widget的派生(或者将公共部分重构为父类GeneralWidget的可能更清晰的解决方案).共同部分并不完全常见.他们的声明和他们的定义看起来是一样的,但因为他们使用特征,所以他们最终完全不同.
最终EDIT2
#include <assert.h>
template<typename Type> struct Widget
{
Widget() {}
char common_fn() { return 'a'; }
int uncommon_fn() { return 1; }
};
template<>
int Widget<char>::uncommon_fn() { return 2; }
int main()
{
Widget<char> WidgetChar;
assert( WidgetChar.common_fn() == 'a' ); // OK
assert( WidgetChar.uncommon_fn() == 2 );
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2144 次 |
| 最近记录: |