avt*_*ton 3 c++ templates metaprogramming c++11
我需要部分专业化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 */ }
}
Run Code Online (Sandbox Code Playgroud)
然后我想专门它为模板参数之一-例如,我希望在考虑特殊的情况B是int,我想保留func0与func1行为完全一样,在普通Foo(或课程,func0()必须回到我的专业Foo&对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' */ }
}
Run Code Online (Sandbox Code Playgroud)
但我想避免复制粘贴func0和func1.
我也可以将Foo类似的东西重命名,FooBase并简单地继承Foo它,但在这种情况下,我不能使用常见的情况作为
Foo<float, float> a;
Run Code Online (Sandbox Code Playgroud)
有什么方法可以让我同时使用它们
Foo<float, float> a;
Run Code Online (Sandbox Code Playgroud)
和
Foo<float, int> b;
Run Code Online (Sandbox Code Playgroud)
没有复制和粘贴常见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"; }
};
Run Code Online (Sandbox Code Playgroud)
如果你最终需要在FooBase中定义Foo,你可能需要使用CRTP技巧将派生类作为模板参数传递给FooBase,但是对于简单的事情,我认为前向声明就足够了.