I don\'t know if it\'s possible but I want to do stuff like
int someval = 1;
if({1,2,3,4}_v.contains(someval ))
but when I try to define l
§13.5.8/3 says:
The declaration of a literal operator shall have a parameter-declaration-clause equivalent to one of the following:
const char* unsigned long long int long double char wchar_t char16_t char32_t const char*, std::size_t const wchar_t*, std::size_t const char16_t*, std::size_t const char32_t*, std::size_t
So it looks like you can't have a parameter of initializer_list
type.
I can only think of the obvious as an alternative; if you don't mind typing a little more you can do something like
std::vector<int> v(std::initializer_list<int> l) {
return { l };
}
int someval = 1;
if(v({1,2,3,4}).contains(someval))
Alternatively you could get wacky and write an operator overload for initializer_list
(haven't tested though):
bool operator<=(std::intializer_list<int> l, int value) {
return std::find(std::begin(l), std::end(l), value) != std::end(l);
}
And
if ({1, 2, 3, 4} <= 3)
should work...
Actually nevermind, it doesn't. You'll have to go with a normal function.
How about this:
#include <initializer_list>
template <typename T>
bool contains(std::initializer_list<T> const & il, T const & x)
{
for (auto const & z : il) { if (z == x) return true; }
return false;
}
Usage:
bool b = contains({1, 2, 3}, 5); // false
you'd expect syntax to be
if value in (value1, value2 ...)
or something similar.
If you're willing to add one extra character, try this syntax:
#include <algorithm>
#include <iostream>
#include <array>
template <typename T0, typename T1, std::size_t N>
bool operator *(const T0& lhs, const std::array<T1, N>& rhs) {
return std::find(begin(rhs), end(rhs), lhs) != end(rhs);
}
template<class T0, class...T> std::array<T0, 1+sizeof...(T)> in(T0 arg0, T...args) {
return {{arg0, args...}};
}
int main () {
if( 2 *in(1,2,3) ) { std::cout << "Hello\n"; }
if( 4 *in(5,6,7,8) ) { std::cout << "Goodbye\n"; }
}