我想在 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/