我有以下代碼,旨在接收一個接受兩個引數的通用函式物件,并回傳一個對另一個順序的引數做同樣處理的函式物件。
#include <type_traits>
#include <functional>
template<typename Function, typename FirstIn
, typename SecondIn, typename std::enable_if<std::is_invocable<Function, FirstIn, SecondIn>:value> ::type>
std::function<typename std::invoke_result<Function, FirstIn, SecondIn>::type( SecondIn, FirstIn)>
swapInput(Function f)
{
return[=](SecondIn b, FirstIn a) { return std::invoke(f, a, b); };
}
int main()
{
std::function<bool(std::string, int)> isLength = [](std::string s, int len) {return(s。 size() == len); };
std::function<bool(int, std::string)> lengthIs =
swapInput<std::function<bool(std::string, int)>, std::string, int> (isLength)。
}
這在分配lengthIs的一行給出了以下編譯器錯誤:
Error C2783 'std::function<std::invoke_result<Function,FirstIn,SecondIn> :type(SecondIn,FirstIn)> swapInput(Function) ' /span>
: 無法推匯出template引數for '__formal'。
錯誤 C2672 'swapInput': 沒有找到匹配的多載函式
我使用的是Visual Studio 19,設定為C 17.
。uj5u.com熱心網友回復:
你對std::enable_if的使用是錯誤的。你需要
template<typename Function, typename FirstIn, typename SecondIn
, typename = std::enable_if_t<
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^。
std::is_invocable_v<Function, FirstIn, SecondIn>
>
>
std::function<std::invoke_result_t<Function, FirstIn, SecondIn>(SecondIn, FirstIn)>
swapInput(Function f)
{
return [=](SecondIn b, FirstIn a) { return std::invoke(f, a, b); };
}
建議:
既然你使用c 17,我建議為swapInput提供auto回傳。
再進一步,如果你重新安排了函式模板的引數,你就不需要在函式呼叫時進行冗長明確的std::function<bool(std::string, int)>。
使用if constexpr,更容易閱讀的代碼:
根據上述建議:
template< typename FirstIn, typename SecondIn, typename Function>
auto swapInput(Function f)
{
if constexpr (std::is_invocable_v<Function, FirstIn, SecondIn >)
return [=](SecondIn b, FirstIn a) { return std::invoke(f, a, b); };
}
現在的函式呼叫將是
std::function<bool(int, std::string)> lengthIs
= swapInput<std::string, int>(isLength)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/329614.html
標籤:
下一篇:為什么C 禁止這種部分專用化?
