提问者:小点点

C++函子,有什么有效的方法吗?


在我的C++代码中,我编写了两个作为参数的函子,一个返回和,另一个返回减法,这样我就可以将它们用作函数的参数。 像这样:

template<class T>
class AddValues{
public:
    T operator()(const T &value1, const T &value2) {
            return value1 + value2;
    }
};

template<class T>
class SubstractValues{
public:
    T operator()(const T &value1, const T &value2) {
        return value1 - value2;
    }
};

但是现在我想写6个函数,每个函数接受两个参数并返回true/false,第一个值是,而另一个值是

有没有更明确的方法来做到这一点,而不是定义6个类? 我用的是C++11


共1个答案

匿名用户

注:此帖是我对原帖评论的精炼。

首先,您应该注意STL已经定义了一组函子。 请参阅比较器下的https://en.cppreference.com/w/cpp/header/functional,以了解<;,<=,>,>=,==,!=以及+,-(已重新定义)的算术运算。 了解STL以及如何使用它是一个很好的实践。

如何使用它们

函子是像任何其他对象一样的对象,要与值语义一起使用。 对于函数外观,它们定义了函数操作符(operator()),并且可以直接在对象上调用()。

std::less is_less;
bool is_0_less_than_0 = is_less(0,1); // Calls bool operator()(int, int) and evaluates to true

函子通常与算法结合使用。 对于一个不太漂亮的用例,比较两个整数数组:

std::array<int,4> low_numbers = {1,2,3,4};
std::array<int,4> high_numbers = {5,6,7,8};
std::array<bool,4> is_number_greater;
// compares low_numbers and high_numbers element wise and stores result in is_number_greater.
std::transform(low_numbers.begin(), 
    low_numbers_low.end(), 
    high_numbers.begin(), 
    is_number_greater.begin(),
    std::greater{}); 

如何编写自己的函子

因此,您已经(从功能角度)重新定义了std::plus(作为AddValues)和std::minus(作为SubtractValues)。 注意,我说的是功能性,因为只模板化函数运算符更灵活:

struct AddValues{
    template<class T>
    T operator()(const T &value1, const T &value2) {
             return value1 + value2;
    }
};

并且由于成员方法运算符()不修改AddValues的任何成员,因此应该将其标记为const:

struct AddValues{
    template<class T>
    T operator()(const T &value1, const T &value2) const {
             return value1 + value2;
    }
};

则在实例化对象时不需要指定类型。 比较模板类:

AddValues<int> add_values; // templated type has to be explicitly written.
add_values(1,2); //=3

使用模板方法:

AddValues add_values;
add_values(1,2); //=3, types deduced when calling method.

无论如何,您必须对,<=,>=,>=,==,!=执行同样的操作,因为您需要围绕每个操作符的包装器。 区别只是现在返回布尔值而不是类型。

struct MyLess
{
    template<typename T>
    bool operator()(const T& lhs, const T& rhs) const { return lhs < rhs; }
};

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++|函|子|方法)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?