2013-03-04 21 views
5

我有一個模板函數C++如何定義一個函數不知道確切的參數

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

如何解決這個問題?不知何故,我記得看到功能輸入 像(...,...)?

+5

要查找的關鍵字:可變長參數列表,可變參數模板。 (然而,你的代碼片段似乎很奇怪,沒有什麼可以傳遞給T的構造函數的。) – us2012 2013-03-04 17:45:43

+2

如果你不知道參數的數量,你怎麼知道要傳遞什麼值? – 2013-03-04 17:47:49

+0

使用此鏈接 http://stackoverflow.com/questions/3307939/c-template-function-with-unknown-number-of-arguments – 2013-03-04 17:52:38

回答

1

這是基於一個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); 
} 

希望它能幫助。祝你好運!

+2

Sh sh,own raw raw poin poin sh sh sh sh sh! – Xeo 2013-03-04 18:07:19

+0

@Xeo:現在怎麼樣? RAII一路。 – 2013-03-04 18:43:29

+0

噓,噓,壞no -'make_unique',噓! ... 開玩笑。 ;) – Xeo 2013-03-04 18:46:24

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還可以提供更多的信息

+2

你的意思是'template '。你的編輯沒有任何意義:-)。您需要將'Args'傳遞給函數,而不是'T'。另外,在將參數傳遞給構造函數時使用'std :: forward'。 – Praetorian 2013-03-04 17:53:24

+0

懶得提供工作示例? :) – 2013-03-04 17:59:46

相關問題