繁体   English   中英

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

[英]Why is a templated function parameter resolved but not a templated return type?

我有以下几段代码:

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函数位于静态库中,该静态库由包含WinMain的项目使用。

返回类型不能由编译器推断。 您可以使用:

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

现场例子

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM