我有模板功能
template <class T>
void foo() {
// Within this function I need to create a new T
// with some parameters. Now the problem is I don't
// know the number of parameters needed for T (could be
// 2 or 3 or 4)
auto p = new T(...);
}
我该如何解决这个问题?不知怎的,我记得看过带输入的函数 喜欢(...,...)?
答案 0 :(得分:6)
您可以使用可变参数模板:
template <class T, class... Args>
void foo(Args&&... args){
//unpack the args
T(std::forward<Args>(args)...);
sizeof...(Args); //returns number of args in your argument pack.
}
This question这里有更多关于如何从可变参数模板解包参数的细节。此question here也可能提供更多信息
答案 1 :(得分:2)
以下是基于variadic template:
的适用于您的C ++ 11示例#include <utility> // for std::forward.
#include <iostream> // Only for std::cout and std::endl.
template <typename T, typename ...Args>
void foo(Args && ...args)
{
std::unique_ptr<T> p(new T(std::forward<Args>(args)...));
}
class Bar {
public:
Bar(int x, double y) {
std::cout << "Bar::Bar(" << x << ", " << y << ")" << std::endl;
}
};
int main()
{
foo<Bar>(12345, .12345);
}
希望它有所帮助。祝你好运!