代码之家  ›  专栏  ›  技术社区  ›  mtijn

为什么解析了模板函数参数而不是模板返回类型?

  •  0
  • mtijn  · 技术社区  · 12 年前

    我有以下代码:

    int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPTSTR lpCmdLine, _In_ int nCmdShow)
    {
        int serialport = getCommandLineOption<int>(lpCmdLine, "-com", atoi);
        ...
    
    template<typename T>
    T getCommandLineOption(const std::string& commandLine, const std::string& option, std::function<T(const char*)> f)
    {
        auto result = getCommandLineOption(commandLine, option);
        return result.empty() ? T() : f(result.c_str());
    }
    
    const std::string getCommandLineOption(std::string commandLine, std::string option)
    {
        ...
    

    然后我删除了 functional 并将模板函数更改为:

    template<typename T, typename F>
    T getCommandLineOption(const std::string& commandLine, const std::string& option, F f)
    {
        auto result = getCommandLineOption(commandLine, option);
        return result.empty() ? T() : f(result.c_str());
    }
    

    现在在 WinMain 在那里我调用函数以获取串行端口参数,我不能省略int类型规范,但我 可以 省略函数指针类型规范。为什么?

    PS: getCommandLineOption 函数位于静态库中,静态库由包含 程序进入点 .

    1 回复  |  直到 12 年前
        1
  •  0
  •   Jarod42    12 年前

    编译器无法推断返回类型。您可以使用:

    template<typename F>
    auto
    getCommandLineOption(const std::string& commandLine, const std::string& option, F f)
    -> decltype(f(getCommandLineOption(commandLine, option).c_str()))
    // or decltype(f(declval<const char*>()))
    {
        auto result = getCommandLineOption(commandLine, option);
        return result.empty() ? decltype(f(result.c_str())){} : f(result.c_str());
    }
    

    Live example