我需要对 struct
进行部分特化,但我还想使用一些通用功能。例如,假设我有下一个类型:
template <typename A, typename B>
struct Foo
{
Foo& func0() { /* common actions with A and B */; return *this; }
void func1() { /* common actions with A and B */ }
void func2() { /* common actions with A and B */ }
}
然后我想专门针对其中一个模板参数 - 例如,当 B
是 int
时,我想考虑特殊情况,并且我想保留 func0
和 func1
的行为与常见的 Foo
完全相同(当然,func0()
必须返回我的专用 Foo&
for int
), func2
我想重写(假设我有更有效的整数实现),我还想添加 func3 ()
仅适用于我专门的 Foo
。
当然,我可以简单的写出如下内容:
template <typename A>
struct Foo<A, int>
{
Foo& func0() { /* common actions with A and B */; return *this; }
void func1() { /* common actions with A and B */ }
void func2() { /* actions with A and 'int' */ }
void func3() { /* actions with A and 'int' */ }
}
但我想避免在 func0
和 func1
中复制粘贴。
我也可以将通用的 Foo
重命名为 FooBase
并简单地从中继承 Foo
,但在这种情况下我不能使用常见情况为
Foo<float, float> a;
哪些方法允许我同时使用这两种方法
Foo<float, float> a;
和
Foo<float, int> b;
没有复制和粘贴通用 Foo
的代码到特化?
我对 c++11 和更早的标准兼容性很感兴趣。
最佳答案
这似乎对我有用。
template <typename A, typename B>
struct Foo;
template <typename A, typename B>
struct FooBase
{
Foo<A, B>& func0()
{
cout << "FooBase:func0\n";
return static_cast<Foo<A, B>&>(*this);
}
void func1() { cout << "FooBase::func1\n"; }
void func2() { cout << "FooBase::func2\n"; }
};
template <typename A, typename B>
struct Foo : public FooBase<A, B> {
};
template <typename A>
struct Foo<A, int> : public FooBase<A, int>
{
void func2() { cout << "Foo<A, int>::func2\n"; }
void func3() { cout << "Foo<A, int>::func3\n"; }
};
如果您最终需要在 FooBase 中定义 Foo,您可能需要使用 CRTP 技巧将派生类作为模板参数传递给 FooBase,但对于简单的事情,我认为前向声明就足够了。
关于具有继承的 C++ 模板部分特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27453449/