c ++ 11:创建函数的最简单方法是返回true以用于函数参数

mr_*_*r_T 3 lambda function c++11

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

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;
    }

    // ...
};
Run Code Online (Sandbox Code Playgroud)

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

我能想到的最好的是:

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

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

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

Sho*_*hoe 8

不确定如何改进 lambda ,但是你可以定义一个通用的lambda,给定任何输入总是返回true(也可以在这里使用):

auto always_true = [](auto&&...) { return true; };
Run Code Online (Sandbox Code Playgroud)

你会用它作为:

auto maximum = collection.maximalEntity(measure, always_true);
Run Code Online (Sandbox Code Playgroud)

Live demo


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

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

然后将用作:

auto maximum = collection.maximalEntity(measure, always_true{});
Run Code Online (Sandbox Code Playgroud)

Live demo