在C++中使用带有boost::mpl::find_if的自定义一元谓词



我有许多不同的类类型,每个类型都有成员函数GetParameterString(),它返回特定于该类的字符串。我希望能够将这些类类型存储在boost::mpl::list中,并将GetParameterString与我从另一个源接收的测试字符串进行比较。因此,如果我有3个类类型,我想做如下操作:

const std::string input_string = "Random String";
using ClassTypes = boost::mpl::list<ClassA, ClassB, ClassC>;
auto it = boost::mpl::find_if<ClassTypes>( [&input_string](auto next_class){
return input_string.compare(next_class.GetParameterString() )
});
it->CallSomeOtherCommonClassMethod();

这里有两个问题。首先,返回值是int而不是bool。但更重要的是,即使我返回bool,我如何设置对boost::mpl::find_if的调用似乎也不正确。

我的要求之一是坚持boost::mpl。提前感谢!

因此,我倾向于相信我对boost::mpl::find_if的使用是不正确的,而不是不将boost::mpl用作类型上使用的仅编译器时间库。作为参考,我在下面使用了boost::mpl::for_each,没有任何问题,并且得到了我想要的:

boost::mpl::for_each<ClassTypes>([&input_string](auto next_class) {
if (next_class.GetParameterString() == input_string) {
// DO SOMETHING
}});

boost::mpl库大多只在编译时使用,它纯粹对类型而非值进行操作(boost::mpl::for_each是一个例外(。其find_if的结果是其中一个类,而不是任何类型的值"λ";传入的也不是通常的C++lambda。

如果getParameterString()static constexpr成员函数,则您可以实现您想要的功能。您需要弄清楚如何创建正确的类型Predicate。一旦你有了它,你的代码应该看起来像:

using ClassTypes = boost::mpl::list<ClassA, ClassB, ClassC>;
using iter = boost::mpl::find_if<ClassTypes, Predicate>::type;
boost::mpl::deref<iter>::type::CallSomeOtherCommonClassMethod();

最新更新