5

テンプレート機能がある

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

これを解決するにはどうすればよいですか?どういうわけか、(...、...) のような入力を持つ関数を見たのを覚えていますか?

4

2 に答える 2

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 here には、可変個引数テンプレートから引数をアンパックする方法の詳細があります。こちらの質問でも詳細情報が得られる場合があります

于 2013-03-04T17:50:33.060 に答える
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);
}

それが役に立てば幸い。幸運を!

于 2013-03-04T17:59:22.167 に答える