如何"帮助"编译器从模板参数中推导出函数模板返回类型?

Ael*_*ian 0 c++ templates c++11 argument-deduction

要从strtoxx调用中去除代码,但仍然将它们内联,我希望有一个函数模板,如:

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

并称之为

unsigned long x = StrToNum<strtoul>( "1984" );
Run Code Online (Sandbox Code Playgroud)

但是我得到'模板参数推断/替换失败:'错误.我可以:

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 );
}
Run Code Online (Sandbox Code Playgroud)

并在调用时指定返回类型.但感觉这是多余的.有没有办法避免它?

我试图在C++ 11中使用'using'来'模板typedef'STR_TO_NUM,但是无法弄清楚如何为函数类型做到这一点.

谢谢

And*_*hko 6

STR_TO_NUM在你的第一个例子中是一个类型.你传递的strtoul是一个函数.您可以尝试以下方式:

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

并称之为:

unsigned long x = StrToNum( "1984", strtoul );
Run Code Online (Sandbox Code Playgroud)

  • 要符合`c ++ 11`,你可以帮助编译器通过` - > decltype推导出结果类型(strToNum(s.c_str(),std :: declval <char**>(),10)) (2认同)