mercredi 9 mai 2018

Template arguments of the first template type

I am using an an API that takes a function with a single argument as a callback. The callback takes a single argument of a certain type, and for simplicity, I'll say it returns a bool. The main thing I was trying to put together was a range checking function. My intuition would be to write something like this:

template<class T, T min, T max>
constexpr bool in_range(T val) {
    return (val >= min && val <= max);
}

static_assert(in_range<float, 0.0f, 1.0f>(0.5f))

However, that doesn't work, so I defaulted to creating a function this way.

template<class T>
std::function<bool(T)> in_range(T min, T max) {
    auto test = [min, max](T val) {
        return (val >= min && val <= max);
    };
    return test;
}


assert(in_range<float>(0.0f, 1.0f)(0.5f))

Is there a way to write the function more in the form of the first function, so I'm not depending on std::function and lambdas generated at runtime?

Aucun commentaire:

Enregistrer un commentaire