lundi 30 juillet 2018

c++ non-type parameter pack expansion

I am writing template function that is parametrized by single type, and has variable number of parameters of the same type (not of different types). It should check if first value is among the rest. I wanted to write it like this:

#include <unordered_set>

template <typename T>
static bool value_in(T val, T vals...) {
    // compiles, but uses only vals[0]:
    const std::unordered_set<T> allowed {vals};
    // error: pack expansion does not contain any unexpanded parameter packs:
    // const std::unordered_set<T> allowed {vals...};
    return allowed.find(val) != allowed.end();
}
// usage
enum class Enumeration {one, two, three};
int main () {
    // should return true -> 0
    return value_in(Enumeration::two,
                    Enumeration::one,
                    Enumeration::two) ? 0 : 1;
}

I expected that second to work, but it doesn't compile because

test.cpp: In function ‘bool value_in(T, T, ...)’:
test.cpp:7:46: error: expansion pattern ‘vals’ contains no argument packs

I see the "(T, T, ...)" instead of "(T, T...), so probably I messed up function declaration and ended with C-style variadic function.

How to write declaration that will accept arbitrary number of parameters of the same type?

Aucun commentaire:

Enregistrer un commentaire