C++区分Functor和Value模板参数

Wor*_*tiz 4 c++ templates overloading functor

一般来说,我在理解仿函数方面遇到了一些麻烦,因为我对模板编程很新.

我在这里要完成的是以下内容,我正在尝试使用一个函数来获取一个Functor和一个带有值的重载函数.

理想情况下:

template<typename ValueType>
int function(ValueType v)
{
    v + 1;
    ...
}

template<typename Functor>
int function(Functor f)
{
    f();
    ...
}
Run Code Online (Sandbox Code Playgroud)

我可以通过将std :: function作为参数来获得性能,但我特别希望能够将lambda作为参数.

编辑

我想要实现的是允许我正构建的构造在必要时进行惰性求值:

construct.option(1)
construct.option([](){ return 5;})
construct.value()
Run Code Online (Sandbox Code Playgroud)

使用构造选择在调用选项时获取哪个参数的值.(可能有一个额外的参数来确定是否选择了该选项)

要明确的是,只要完成此选项调用,它就会知道是否评估表达式.

此外,如果参数重载了()运算符,我想调用它,不管它是否也重载+ 1.

Wal*_*ter 6

是的,你可以使用SFINAE做到这一点:

// overload taking functor f(int)
template<typename Func>
std::result_of_t<Func(int)>   // or std::invoke_result_t<> (C++17)
function(Func const&func)
{
    return func(0);
}

// overload taking value of builtin arithmetic type
template<typename ValueType>
enable_if_t<std::is_arithmetic<ValueType>::value, ValueType>
function(Value const&val)
{
    return val;
}
Run Code Online (Sandbox Code Playgroud)

  • 在C++ 17中你有[std :: is_invocable(_r)](https://en.cppreference.com/w/cpp/types/is_invocable)这比检查转换为`std :: function要好一点`. (4认同)