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.
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.
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.
All the operators above except _r and _t are cooked literals.
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 .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With