我可以使用可變參數模板而不使用模板參數作爲功能參數嗎?無功能參數的可變模板
當我使用它們,它編譯:
#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>();
}
不幸的是,我班想要作爲模板參數給出不可實例化(它們具有在模板函數內部調用的靜態函數)。 有沒有辦法做到這一點?
如果你需要一個給定類型的*未計算*表達,你可以用'的std :: declval()'。適用於任何'T',不管它是否可以構造。 –
2012-04-23 10:25:59
至於爲什麼沒有參數的版本不起作用:沒有參數,'print'和print '同樣好,而參數'print (3)'比'print 更好匹配(3,{})'(其中'{}'表示「無」)。正如CatPusPus所建議的,不使用重載是標準方法;因爲無論如何你都不會推論你的論點,這是最簡單的解決方案。 –
2012-04-23 10:30:55
我打算髮表一個答案,但中午。已經發布了它。 – bames53 2012-04-23 20:57:54