Zeks
Zeks

Reputation: 2375

Initializer list in user-defined literal parameter

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 literal as:

std::vector<int> operator"" _v ( std::initializer_list<int> t )
{
    return std::vector<int> (t);
}

to accept initializer list of ints I get

 error: 'std::vector<int> operator"" _v(std::initializer_list<int> t)' has invalid argument list

Is there a way to do this? What I really want is to finally be rid of stuff like

if(value == 1 || value ==2 || value == 3 ...

Having to write stuff like this is really annoying, because you'd expect syntax to be

if value in (value1, value2 ...) 

or something similar.

Upvotes: 9

Views: 3218

Answers (3)

Robᵩ
Robᵩ

Reputation: 168636

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

Upvotes: 6

Seth Carnegie
Seth Carnegie

Reputation: 75130

§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.

Upvotes: 5

Kerrek SB
Kerrek SB

Reputation: 477100

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

Upvotes: 8

Related Questions