Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializer list in user-defined literal parameter

Tags:

c++

c++11

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.

like image 264
Zeks Avatar asked Jan 16 '13 21:01

Zeks


People also ask

How do you initialize a list in C++?

When do we use Initializer List in C++? Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. Following is an example that uses the initializer list to initialize x and y of Point class.

How do you define a literal in C++?

Literals are data used for representing fixed values. They can be used directly in the code. For example: 1 , 2.5 , 'c' etc. Here, 1 , 2.5 and 'c' are literals.

Which operators are not used with literals?

All the operators above except _r and _t are cooked literals.

What is std :: Initializer_list?

std::initializer_list This type is used to access the values in a C++ initialization list, which is a list of elements of type const T .


1 Answers

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
like image 181
Kerrek SB Avatar answered Nov 11 '22 14:11

Kerrek SB