2017-07-14 65 views
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++?

任何指针,我在做什么错在这里?

+1

您需要使用的模板。你可以做的是'static_assert',这些类型是你期望的,或者SFINAE,这些类型是你期望的 – Justin

+0

可能的重复[C++中可变参数数量?](https://stackoverflow.com/questions/1657883/variable-of-arguments-in-c) – Justin

+0

谢谢,把它变成模板修复了这个问题。 – chrise

回答

1

请尝试以下方法:

static std::string getFromNodeDefault(MiniNode* node, std::string& def,std::string& key) { 
    try { 
     return node->getAttributeString(key); 
    } 
    catch (...) { 
     return def; 
    } 
} 
template<typename... T> 
static std::string getFromNodeDefault(MiniNode* node, std::string& def, 
std::string& key, T&... args) { 
    try { 
     return getFromNodeDefault(node->getChildByKey(key), def, args...); 
    } 
    catch (...) { 
     return def; 
    } 
}