【发布时间】:2014-12-12 23:00:16
【问题描述】:
我需要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& 为int),func2 我想重写(假设我对整数有更有效的实现),我还想添加@ 987654333@ 仅供我专业的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 和更早的标准兼容性都感兴趣。
【问题讨论】:
-
Piotr S 在这里给出了很好的答案stackoverflow.com/questions/27444624/…
-
@JayMiller,情况略有不同——我不仅想更改部分情况的基本方法,还想在特殊类型中添加特定方法。
标签: c++ templates c++11 metaprogramming