2012-04-23 106 views
7

我可以使用可變參數模板而不使用模板參數作爲功能參數嗎?無功能參數的可變模板

當我使用它們,它編譯:

#include <iostream> 
using namespace std; 

template<class First> 
void print(First first) 
{ 
    cout << 1 << endl; 
} 

template<class First, class ... Rest> 
void print(First first, Rest ...rest) 
{ 
    cout << 1 << endl; 
    print<Rest...>(rest...); 
} 

int main() 
{ 
    print<int,int,int>(1,2,3); 
} 

但是,當我不使用他們,這不編譯和抱怨的歧義:

#include <iostream> 
using namespace std; 

template<class First> 
void print() 
{ 
    cout << 1 << endl; 
} 

template<class First, class ... Rest> 
void print() 
{ 
    cout << 1 << endl; 
    print<Rest...>(); 
} 

int main() 
{ 
    print<int,int,int>(); 
} 

不幸的是,我班想要作爲模板參數給出不可實例化(它們具有在模板函數內部調用的靜態函數)。 有沒有辦法做到這一點?

+1

如果你需要一個給定類型的*未計算*表達,你可以用'的std :: declval ()'。適用於任何'T',不管它是否可以構造。 – 2012-04-23 10:25:59

+4

至於爲什麼沒有參數的版本不起作用:沒有參數,'print '和print '同樣好,而參數'print (3)'比'print 更好匹配(3,{})'(其中'{}'表示「無」)。正如CatPusPus所建議的,不使用重載是標準方法;因爲無論如何你都不會推論你的論點,這是最簡單的解決方案。 – 2012-04-23 10:30:55

+0

我打算髮表一個答案,但中午。已經發布了它。 – bames53 2012-04-23 20:57:54

回答

20
template<class First> // 1 template parameter 
void print() 
{ 
    cout << 1 << endl; 
} 

#if 0 
template<class First, class ... Rest> // >=1 template parameters -- ambiguity! 
void print() 
{ 
    cout << 1 << endl; 
    print<Rest...>(); 
} 
#endif 

template<class First, class Second, class ... Rest> // >=2 template parameters 
void print() 
{ 
    cout << 1 << endl; 
    print<Second, Rest...>(); 
} 
+1

您可以通過從最底層版本調用'print ()'而不是重複'cout'行來擺脫代碼重複。我認爲。 – 2016-07-30 17:52:45

8

使之成爲一種類型。

template <typename... Ts> 
struct print_impl; 

template <typename T> 
struct print_impl<T> { 
    static void run() { 
     std::cout << 1 << "\n"; 
    } 
}; 

template <typename T, typename... Ts> 
struct print_impl<T, Ts...> { 
    static void run() { 
     std::cout << 1 << "\n"; 
     print_impl<Ts...>::run(); 
    } 
}; 

template <typename... Ts> 
void print() { 
    print_impl<Ts...>::run(); 
} 

int main() { 
    print<int, int, int>(); 
    return 0; 
} 
+0

我認爲這裏的複雜性並不值得。 n.m.的解決方案更直接。 – bames53 2012-04-23 20:58:07