用户定义的文字参数中的初始化列表

Zek*_*eks 8 c++ c++11

我不知道是否可能,但我想做的事情

int someval = 1;
if({1,2,3,4}_v.contains(someval ))
Run Code Online (Sandbox Code Playgroud)

但是当我尝试将文字定义为:

std::vector<int> operator"" _v ( std::initializer_list<int> t )
{
    return std::vector<int> (t);
}
Run Code Online (Sandbox Code Playgroud)

接受我得到的初始化列表

 error: 'std::vector<int> operator"" _v(std::initializer_list<int> t)' has invalid argument list
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?我真正想要的是最终摆脱像这样的东西

if(value == 1 || value ==2 || value == 3 ...
Run Code Online (Sandbox Code Playgroud)

写这样的东西真的很烦人,因为你期望语法

if value in (value1, value2 ...) 
Run Code Online (Sandbox Code Playgroud)

或类似的东西.

Ker*_* SB 7

这个怎么样:

#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;
}
Run Code Online (Sandbox Code Playgroud)

用法:

bool b = contains({1, 2, 3}, 5);  // false
Run Code Online (Sandbox Code Playgroud)


Rob*_*obᵩ 6

你希望语法是

if value in (value1, value2 ...) 
Run Code Online (Sandbox Code Playgroud)

或类似的东西.

如果您愿意添加一个额外的字符,请尝试以下语法:

#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"; }
}
Run Code Online (Sandbox Code Playgroud)


Set*_*gie 5

\xc2\xa713.5.8/3 说:

\n
\n

文字运算符的声明应具有相当于以下其中一项的\n参数声明子句:

\n
const char*\nunsigned long long int\nlong double\nchar\nwchar_t\nchar16_t\nchar32_t\nconst char*, std::size_t\nconst wchar_t*, std::size_t\nconst char16_t*, std::size_t\nconst char32_t*, std::size_t\n
Run Code Online (Sandbox Code Playgroud)\n
\n

所以看起来你不能有initializer_list类型参数。

\n

我只能想到显而易见的替代方案;如果你不介意多输入一点,你可以这样做

\n
std::vector<int> v(std::initializer_list<int> l) {\n    return { l };\n}\n\nint someval = 1;\nif(v({1,2,3,4}).contains(someval))\n
Run Code Online (Sandbox Code Playgroud)\n

或者,您可以变得古怪并为以下内容编写运算符重载initializer_list(但尚未测试):

\n
bool operator<=(std::intializer_list<int> l, int value) {\n    return std::find(std::begin(l), std::end(l), value) != std::end(l);\n}\n
Run Code Online (Sandbox Code Playgroud)\n

\n
if ({1, 2, 3, 4} <= 3)\n
Run Code Online (Sandbox Code Playgroud)\n

应该管用...

\n

其实没关系,不是的。你必须使用正常的功能。

\n