想象一下這樣的代碼:可變參數模板選擇比較常見的模板,而不是超載
#include <iostream>
void PrintInternal() {
std::cout << std::endl;
}
template <typename T, typename...ARGS>
void PrintInternal(const T& head, const ARGS&...rest) {
std::cout << head << " ";
PrintInternal(rest...);
};
template <typename...ARGS>
void PrintInternal(const double& head, const ARGS&...rest) {
std::cout << "DBL!!! " << head << " ";
PrintInternal(rest...);
}
template <typename...ARGS>
void Print(const ARGS&...args) {
PrintInternal(args...);
}
int main() {
Print(1.1, 2, 3.3, 4);
Print(0, 1.1, 2, 3.3, 4);
return 0;
}
首先Print
輸出:
DBL! 1.1 2 3.3 4
我的期望是,它會輸出DBL! 3.3之前還是沒有DBL!在所有。但爲什麼一個?
二Print
輸出:
0 1.1 2 3.3 4
爲什麼沒有DBL !!!如果我們在第一個例子中有一個,那麼輸出就像是一樣。
以及如何實現,每個double
我會輸出一些不同的部分專業化?我想,這簡單的重載應該沒問題......
鏈接cpp.sh查看編譯結果 - >http://cpp.sh/42cz
仔細看看,小心。第二個打印有0作爲第一個參數,對不對? (0假設有整數類型)。你的「DBL !!」將第一個參數作爲double。 說,如果你試過0或0.0它會工作 –
是的,你在這裏是正確的,謝謝,但是,更多的奧祕仍未解決:) – Starl1ght
模板函數的順序是重要的。在調用之前,模板調用的所有函數都需要可見。 – NathanOliver