vendredi 28 octobre 2016

How to 'help' the compiler to deduce function template return type from a template parameter which is a function?

To de-clutter code from strtoxx calls, but still have them inlined, I would like to have a function template like:

template <typename STR_TO_NUM> static auto StrToNum( const string& s ) {
    char* pEnd;
    return STR_TO_NUM( s.c_str(), &pEnd, 10 );
}

And call it like

unsigned long x = StrToNum<strtoul>( "1984" );

However I get 'template argument deduction/substitution failed:' error. I can do:

template <typename T, T (*STR_TO_NUM)(const char *, char **, int)> static T StrToNum( const string& s ) {
    char* pEnd;
    return STR_TO_NUM( s.c_str(), &pEnd, 10 );
}

And specify the return type when calling. But it feels like that is redundant. Is there a way to avoid it?

I tried to 'template typedef' STR_TO_NUM using 'using' in C++11, but couldn't figure out how to do that for function types.

Thanks

Aucun commentaire:

Enregistrer un commentaire