用户定义文字参数中的初始化程序列表 [英] Initializer list in user-defined literal parameter

查看:42
本文介绍了用户定义文字参数中的初始化程序列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道是否可行,但我想做类似的事情

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

或类似的东西。

推荐答案



您希望语法为

you'd expect syntax to be

if value in (value1, value2 ...) 

或类似的东西。


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

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

这篇关于用户定义文字参数中的初始化程序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆