Return both string and integer from a template function in C++

ist*_*tik 3 c++ templates if-statement

I am trying to write a generic function, using template, that is able to return bool, integer or char* or string.

template<typename entryType>
entryType getEntry(xml_node node, const char* entryKey)
{
    ...

    if (is_same<entryType, bool>::value) {
         return boolvalue; //returning a boolean
    }
    else if(is_same<entryType, int>::value) {
         return a; //this is an integer
    }
    else if (is_same<entryType, char*>::value) {
         return result; //this is a char*
    }
}
Run Code Online (Sandbox Code Playgroud)

and I would like to be able to call it like:

bool bPublisher = getEntry<bool>(node, "Publisher");
int QoS = getEntry<int>(node, "QualityOfService");
char* sBrokerUrl = getEntry<char*>(node, "BrokerUrl");
Run Code Online (Sandbox Code Playgroud)

as an alternative for the char*, a string would be also fine:

string sBrokerUrl = getEntry<string>(node, "BrokerUrl");
Run Code Online (Sandbox Code Playgroud)

I get errors like: "cannot convert from 'bool' to 'char*'. I understand the problem, the compiler is not able to detect that the code execution branch depends on the type I give. I just can't find a solution for that. Could anyone help me? Thanks.

son*_*yao 5

Since C++17 you can use constexpr if; whose condition part will be evaluated at the compile time, and if the result is true then the statement-false part (otherwise the statement-true part) will be discarded. (Thus won't cause the error.) e.g.

if constexpr (is_same<entryType, bool>::value) {
     return boolvalue; //returning a boolean
}
else if constexpr (is_same<entryType, int>::value) {
     return a; //this is an integer
}
else if constexpr (is_same<entryType, char*>::value) {
     return result; //this is a char*
}
Run Code Online (Sandbox Code Playgroud)

LIVE

  • @P0W 关于 FGITW (2认同)