function - C++11 : easiest way to create a function always returning true to use for a function argument

标签 function c++11 lambda

我想使用以下模板成员函数

template <typename Entity>
class SomeCollection
{
    // ....

    template <typename Measure, typename Filter>
    Entity maximalEntity(Measure&& measure, Filter&& requirement)
    {
        auto maxEntity = Entity();
        auto maxValue = -std::numeric_limits<double>::infinity();

        for (auto ent /* some iteration method*/)
        {
            auto measurement = measure(ent);
            if (requirement(ent) && measurement > maxValue)
                std::tie(maxEntity, maxValue) = std::make_tuple { ent, measurement };
        }
        return maxEntity;
    }

    // ...
};

在没有过滤器要求的情况下从客户端代码调用此函数的最佳方法是什么(仅具有最大元素)?

我能想到的最好的办法是:

class Something;
double measure(Something&);
SomeCollection<Something> collection;

auto maximum = collection.maximalEntity(measure, [](const Something&) { return true; });

但我想这个 lambda 函数可以改进吗?

最佳答案

不确定如何改进 lambda,但您可以定义一个通用 lambda,给定任何输入都将始终返回 true(也可以在此处使用):

auto always_true = [](auto&&...) { return true; };

您可以将其用作:

auto maximum = collection.maximalEntity(measure, always_true);

Live demo

<小时/>

C++11 的等效实现如下:

struct always_true {
    template<typename... Args>
    bool operator()(Args&&...) const noexcept {
        return true;
    }
};

然后将用作:

auto maximum = collection.maximalEntity(measure, always_true{});

Live demo

关于function - C++11 : easiest way to create a function always returning true to use for a function argument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40631679/

相关文章:

javascript - 更新产品数量而不进行回发

c - 为什么这个c程序会崩溃?

c++ - 我需要遍历一个结构

multithreading - C++ 11线程没有匹配的函数调用

c# - Linq 从另一个区间列表中选择任何区间内的所有数字

android - 如何将 Lambda 转换为简单的 Java 函数表达式

c# - Console.ReadLine() 函数不起作用

javascript - 是否可以检查函数是 javascript 函数还是开发人员定义的函数?

c++ - 使用线程和 this_thread::yield 来确定打印顺序

java - filter和findFirst后map抛出异常需要继续过滤Java流