1
我正在嘗試編寫一個遍歷變量深度的XML節點並查找值的函數。遞歸可變參數函數似乎是一個很好的解決方案,所以我想這個C++ variadic函數
struct MiniNode {
std::string getAttributeString(std::string s) {}
MiniNode getChildByKey(std::string s) {}
};
static std::string getFromNodeDefault(MiniNode* node, std::string& def, std::string& key) {
try {
return node->getAttributeString(key);
} catch (...) {
return def;
}
}
static std::string getFromNodeDefault(MiniNode* node, std::string& def, std::string& key, std::string&... args) {
try {
return getFromNodeDefault(node->getChildByKey(key), def, args...);
} catch (...) {
return def;
}
}
但編譯器抱怨
main.cpp:20:91: error: expansion pattern 'Args&' contains no argument packs main.cpp: In function 'std::string getFromNodeDefault(MiniNode*, std::string&, T&)':
main.cpp:22:67: error: 'args' was not declared in this scope
return getFromNodeDefault(node->getChildByKey(key), def, args...);
我把這裏作爲一個例子,第二個答案的部分,而無需使用模板因爲我知道我的類型 Variable number of arguments in C++?
任何指針,我在做什麼錯在這裏?
您需要使用的模板。你可以做的是'static_assert',這些類型是你期望的,或者SFINAE,這些類型是你期望的 – Justin
可能的重複[C++中可變參數數量?](https://stackoverflow.com/questions/1657883/variable-of-arguments-in-c) – Justin
謝謝,把它變成模板修復了這個問題。 – chrise