如何在 c++ 模板中拥有多个类型名参数?
#ifndef _CALL_TEMP_H
#define _CALL_TEMP_H
#include <string>
#include <iostream>
template <typename Sig>
class Foo;
template <typename A, typename B>
class Foo
{
public:
void output() {
std::cout << a_ << b_ << std::endl;
}
A a_;
B b_;
};
template <typename A, typename B, typename C>
class Foo
{
public:
void output() {
std::cout << a_ << b_ << c_ << std::endl;
}
A a_;
B b_;
C c_;
};
#endif
用法:
int main()
{
Foo<int ,int> doubleint;
doubleint.a_ = 1;
doubleint.b_ = 2;
doubleint.output();
// Foo<int , int , std::string> comp;
// comp.a_ = 1;
// comp.b_ = 2;
// comp.c_ = "haha";
// comp.output();
return 0;
}
但它不会编译。我怎样才能让它编译?
最佳答案
只需使用可变参数模板声明一个主模板,然后专门针对每个支持的模板参数数量。例如:
#ifndef CALL_TEMP_H
#define CALL_TEMP_H
#include <iostream>
template <typename...> class Foo;
template <typename A, typename B>
class Foo<A, B>
{
public:
void output() {
std::cout << a_ << b_ << '\n';
}
A a_;
B b_;
};
template <typename A, typename B, typename C>
class Foo<A, B, C>
{
public:
void output() {
std::cout << a_ << b_ << c_ << '\n';
}
A a_;
B b_;
C c_;
};
#endif
您不能使用 C++11,并且您想保留类似的符号,您需要使用模板默认参数模拟可变参数列表。这将隐式限制 templare 参数的数量,但由于无论如何您都在专门化模板,所以这个限制并不重要。
如果可以接受使用不同的符号,您也可以使用类似于函数声明的东西来实例化和专门化您的模板:
template <typename> class Foo;
template <typename A, typename B>
class Foo<void(A, B)> {
...
};
template <typename A, typename B, typename C>
class Foo<void(A, B, C)> {
...
};
...
Foo<void(int, int)> f2;
Foo<void(int, int, std::string)> f3;
符号的变化是否可以接受取决于您对类模板的使用。但是,如果没有 C++11,您将无法获得理想的解决方案。
顺便说一句,don't overuse std::endl
: 使用 '\n'
表示行尾。如果您真的要刷新流,请使用 std::flush
。此外,_CALL_TEMP_H
是标准 C++ 库保留的名称,所有以下划线后跟大写字符的名称也是如此:不要在您自己的代码中使用这些名称,除非有是使用它们的明确许可(例如,__FILE__
和 __LINE__
被保留,但被授予使用它们的明确许可)。
关于c++ - c++模板中的多个类型名参数? (可变参数模板),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19923353/