[英]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.