【问题标题】:How to 'help' the compiler to deduce function template return type from a template parameter which is a function?如何“帮助”编译器从作为函数的模板参数中推断出函数模板返回类型?
【发布时间】:2016-10-28 15:23:05
【问题描述】:

为了从 strtoxx 调用中整理代码,但仍将它们内联,我想要一个函数模板,例如:

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

然后这样称呼它

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

但是我收到“模板参数推导/替换失败:”错误。我能做到:

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

并在调用时指定返回类型。但感觉那是多余的。有办法避免吗?

我尝试在 C++11 中使用“使用”来“模板 typedef”STR_TO_NUM,但不知道如何为函数类型执行此操作。

谢谢

【问题讨论】:

    标签: c++ c++11 templates template-argument-deduction


    【解决方案1】:

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

    并将其称为:

    unsigned long x = StrToNum( "1984", strtoul );
    

    【讨论】:

    • 要符合c++11,您可以帮助编译器通过-&gt; decltype(strToNum(s.c_str(), std::declval&lt;char **&gt;(), 10 )) 推断结果类型
    • 谢谢。我的意思是使用 strtoxx 一个值参数并让编译器从那里推断出所有内容。我相信这样编译器可以内联 strtoxx。
    • 作为一个纯粹的猜测:值得尝试链接时优化(或整个程序优化),所有主要编译器都可用,看看函数调用是否被内联,尽管指针指向函数。跨度>
    【解决方案2】:

    C++17 有:

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

    而不是

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

    及其

    StrToNum<decltype(&strtoul), &strtoul>("1984");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多