简体   繁体   English

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

[英]C++ distinguish Functor and Value template argument

In general I'm having some trouble understanding functors, as I'm fairly new with template programming. 一般来说,我在理解仿函数方面遇到了一些麻烦,因为我对模板编程很新。

What I'm trying to accomplish here is the following, I'm trying to have a function that takes a Functor and an overloaded function that takes a value. 我在这里要完成的是以下内容,我正在尝试使用一个函数来获取一个Functor和一个带有值的重载函数。

ideally: 理想情况下:

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

template<typename Functor>
int function(Functor f)
{
    f();
    ...
}

I would be fine taking a performance hit with something like taking an std::function as parameter, but I especially want to be able to take a lambda as parameter. 我可以通过将std :: function作为参数来获得性能,但我特别希望能够将lambda作为参数。

EDIT 编辑

What I'm trying to achieve is to allow a construct I'm building to have lazy evaluation when necessary: 我想要实现的是允许我正构建的构造在必要时进行惰性求值:

construct.option(1)
construct.option([](){ return 5;})
construct.value()

With the construct choosing which argument's value to get when option is called. 使用构造选择在调用选项时获取哪个参数的值。 (likely with an extra argument determining whether that option is chosen) (可能有一个额外的参数来确定是否选择了该选项)

To be clear, as soon as this option call is done, it knows whether to evaluate the expression or not. 要明确的是,只要完成此选项调用,它就会知道是否评估表达式。

Also if the argument overloads the () operator, I want to call it, regardless of it overloads the + 1 too. 此外,如果参数重载了()运算符,我想调用它,无论它是否也重载+ 1。

Yes, you can do that using SFINAE : 是的,你可以使用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;
}

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

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