c++ - 没有 cruft 的 C++ "in"运算符?

标签 c++ c++11

我想在 C++ (11) 中模拟 Python 的 in 运算符,就像在 Python 中一样使用即时值。如:

if x in (1, 2, 3): ...

在 C++11 中,我似乎接近能够做到这一点:

if (IsIn(x, { 1, 2, 3 }))
    {
    }


template<typename Val, Container cont>
bool IsIn(Val const &val, Container const &cont)
    {
    return boost::find(cont, val) != cont.end();
    }

但是(在 g++-4.8 中)我得到:

error: no matching function for call to 'IsIn(MyType&, <brace-enclosed initializer list>)'

我知道我可以做到这一点,但这有很多麻烦:

if (IsIn(x, std::initializer_list<MyType>{1, 2, 3 })) ...

优雅的解决方案是什么?

更新:我对编译时与运行时的思考不够充分,我仍然无法决定是否有明显的赢家。我的 IsIn(x, {}) 肯定有更多的运行时循环开销并复制 initializer_list 值,但也适用于任何容器。 ... == any_of(... 机制肯定会编译成更紧凑的代码并且不会复制,但只适用于立即数(这是我最初的例子)而不是容器,以及语法(对我来说)似乎不太直截了当。

由于这是一种领带,我将其授予贡献者以示感谢。

感谢大家的讨论!

最佳答案

解决方案就在我眼皮底下......

template<typename Val>
bool IsIn(Val val, std::initializer_list<Val> const &cont)
    {
    return boost::find(cont, val) != cont.end(); // include <boost/range/algorithm.hpp>
    // Or if you don't want boost, include <algorithm>
    // return std::find(cont.begin(), cont.end(), val) != cont.end();
    }

关于c++ - 没有 cruft 的 C++ "in"运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30683306/

相关文章:

c++ - 应用程序 VS Express 2012 c++ 的设置图标

c++ - 将 string 类型转换为 unsigned int 时出现故障

c++ - g++ 和 clang 使用递归可变参数模板位集创建的不同行为(可能是 gcc 错误?)

c++ - 在从抽象基类继承的类中添加方法?

c++ - 在 vector 之间使用 std::swap 还是 vector::swap?

C++ 模板和类

c++ - 将 volatile 数据与未为 volatile 数据重载的方法一起使用

c++ - 通过重复指定长度的条目生成有序选择

c++ - 允许复制列表初始化和显式构造函数吗?

c++ - 获取 std::stack 后面的容器