我有一个采用2个参数的模板。对于第一个参数的某个值,我知道第二个参数应该是什么。我只想对模板进行一个完整定义(一个带有2个参数的定义),并且能够实例化仅提供一个参数的模板。
[在下面的示例中,我知道如果第一个模板参数为Foo1
,则第二个参数应为Foo2
。我希望能够通过编写Someclass<Foo1,Foo2>
创建一个Someclass<Foo1>
。
#include <iostream>
using namespace std;
struct Foo1 { Foo1() { cout << "Foo1 "; }};
struct Foo2 { Foo2() { cout << "Foo2 "; }};
template <typename ...Dummy> struct SomeClass;
template <typename T, typename U> struct SomeClass<T,U> {
SomeClass() {
T t;
U u;
}
};
/* Here, some one-argument specialization where if SomeClass<Foo1> is desired,
* SomeClass<Foo1, Foo2> is obtained. */
int main() {
SomeClass<Foo1, Foo2> c; //prints "Foo1 Foo2 "
SomeClass<Foo1> c2; //Should print the same thing, right now "incomplete type"
}
我想我将不得不进行一个专门化,它需要两个参数,第一个是“ Foo1”,就像这样:
template <typename U> struct SomeClass<Foo1, U> {
SomeClass() {
Foo1 f;
U u;
}
};
但是我如何进行仅接受一个参数“ Foo1”并产生SomeClass的专业化?
template <> struct SomeClass<Foo1>:SomeClass<Foo1,Foo2> {};
对于类模板的情况,最简单的解决方案可能是进行匹配您感兴趣的情况的特殊化,并通过继承继承该目标而将其“转发”到该特殊化。从它:
template <typename ...Dummy>
struct SomeClass
{
// default implementation
};
template <typename T, typename U>
struct SomeClass<T, U>
{
// case for two parameters
};
template <> struct SomeClass<Foo1> : public SomeClass<Foo1, Foo2> {};