c ++如何在不知道确切参数的情况下定义函数

Wha*_*rld 5 c++ templates

我有一个模板功能

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)

我该如何解决这个问题?不知怎的,我记得看到函数输入像(...,...)?

Ton*_*ion 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.
}
Run Code Online (Sandbox Code Playgroud)

这里的这个问题有关于如何从可变参数模板中解包参数的更多细节.这里的这个问题也可能提供更多信息

  • 你的意思是`模板<class T,class ... Args>`.你的编辑没有任何意义:-).你需要将`Args`传递给函数,而不是`T`.另外,在将参数传递给构造函数时使用`std :: forward`. (2认同)

小智 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)

希望能帮助到你。祝你好运!