gpt4 book ai didi

C++ 可变参数函数

转载 作者:行者123 更新时间:2023-11-30 05:11:21 26 4
gpt4 key购买 nike

我正在尝试编写一个函数来遍历可变深度的 XML 节点并找到一个值。递归可变参数函数似乎是一个很好的解决方案,所以我尝试了这个

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 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;
}
}

关于C++ 可变参数函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45093313/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com