我需要部分专业化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
is int
,我想保留func0
and 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
and func1
.
我也可以重命名常见的Foo
类似的东西FooBase
并简单地继承Foo
来自它,但在这种情况下我不能使用常见情况
Foo<float, float> a;
存在哪些方法可以让我同时使用
Foo<float, float> a;
and
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,但对于简单的事情,我认为前向声明就足够了。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)