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

c++ how to define a function without knowing the exact parameters

本文关键字:情况 情况下 下定义 函数 参数 不知道 c++      更新时间:2023-10-16

我有一个模板函数

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(...);
}

如何解决这个问题?不知怎么的,我记得见过带输入的函数像(…,……)?

您可以使用可变模板:

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.
}

这里的问题有更多关于如何从可变模板解压缩参数的细节。这里的问题也可以提供更多的信息

下面是基于可变模板的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);
}

希望有帮助。好运!