1

I am trying to write a function that walks through an XML node of variable depth and finds a value. A recursive variadic function seemed like a good solution, so I tried this

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

But the compiler is complaining that

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...);    

I took parts of the second answer here as an example, without using the template as I know my type Variable number of arguments in C++?

Any pointers to what I am doing wrong here?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
chrise
  • 4,039
  • 3
  • 39
  • 74
  • 1
    You need to use the template. What you can do is `static_assert` that the types are what you expect, or SFINAE that the types are what you expect – Justin Jul 14 '17 at 01:45
  • Possible duplicate of [Variable number of arguments in C++?](https://stackoverflow.com/questions/1657883/variable-number-of-arguments-in-c) – Justin Jul 14 '17 at 01:47
  • thanks, turning this into a template fixed the problem. – chrise Jul 14 '17 at 02:05
  • @Justin. I referred to that question, not sure it s a duplicate. It wasnt totally clear to me that one has to use templates. – chrise Jul 14 '17 at 02:07
  • Hardly you can compile this - `std::string&... args`. – skypjack Jul 14 '17 at 05:17

1 Answers1

1

Please try the following:

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;
    }
}
PrashanthBC
  • 275
  • 1
  • 10