我有一个模板功能
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(...);
}
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个问题?不知怎的,我记得看到函数输入像(...,...)?
您可以使用可变参数模板:
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.
}
Run Code Online (Sandbox Code Playgroud)
这里的这个问题有关于如何从可变参数模板中解包参数的更多细节.这里的这个问题也可能提供更多信息
小智 2
以下是基于可变参数模板的 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);
}
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你。祝你好运!