c++ - 避免模​​板特化中的函数定义重复

标签 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 );
}

开始编辑

致阿尔夫:

我无法使用

template<> int Widget<char>::uncommon_fn() { return 2; }

因为一些不常见的函数需要返回特征类型(因此通过将实际类型设为原语来简化是过度的)。

或者实际上有没有办法让编译器在编写时识别typename Foo::Bar

struct Foo { typedef FooBar Bar; };
template<> typename Foo::Bar Widget<Foo>::uncommon_fn() { return ....; }

?

结束编辑

开始编辑2

致 iammilind:

这很有趣,但出于同样的原因,我无法使用 Widget 的派生(或者可能更清晰的将公共(public)部分重构到父类 GeneralWidget 的解决方案)。公共(public)部分并不完全公共(public)。它们的声明和定义看起来相同,但因为它们使用特征,所以它们最终完全不同。

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

关于c++ - 避免模​​板特化中的函数定义重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7116610/

相关文章:

c++ - 任何指针类型的模板特化

javascript - 如何在 Windows 8 模板中为元素添加新类?

c++ - 可变模板的部分特化需要第一个非可变模板参数

c++ - 专门化嵌套模板

c++ - 假设没有编译器优化,这个对象会被创建多少次?

c++ - 计算题C++

android - 如何使用 Malloc Debug 检查 native 内存泄漏?

C++ 版本的 <?扩展另一个类>

html - 我如何在 QCheckbox 的文本描述中使用 <sub></sub>?

c++ - 未定义对完整模板特化类成员函数的引用,但不是部分特化