【发布时间】:2020-04-09 03:26:04
【问题描述】:
我有一个带有 2 个参数的模板。对于第一个参数的某个值,我知道第二个参数应该是什么。我希望我的模板只有一个完整的定义(带有 2 个参数的那个),并且能够实例化我的模板,只提供一个参数。
在下面的例子中,我知道如果第一个模板参数是Foo1,那么第二个应该是Foo2。我希望能够通过编写Someclass<Foo1> 来创建Someclass<Foo1,Foo2>。
#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"
}
我想我将不得不做一个接受 2 个参数的专业化,第一个是 Foo1,如下所示:
template <typename U> struct SomeClass<Foo1, U> {
SomeClass() {
Foo1 f;
U u;
}
};
但是我如何进行只接受一个参数Foo1 并导致SomeClass<Foo1,Foo2> 的特化?
【问题讨论】:
标签: c++ c++11 templates variadic-templates template-specialization