【问题标题】:Using Custom Unary Predicates With boost::mpl::find_if in C++在 C++ 中使用带有 boost::mpl::find_if 的自定义一元谓词
【发布时间】:2020-10-26 23:21:28
【问题描述】:

我有许多不同的类类型,每个都有成员函数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。提前致谢!

【问题讨论】:

    标签: c++ boost boost-mpl


    【解决方案1】:

    所以我倾向于相信我对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
         }});
    

    【讨论】:

    • 请删除此答案并将其作为您问题的一部分。
    【解决方案2】:

    boost::mpl 库主要是仅编译时的,它纯粹对类型而不是值进行操作(boost::mpl::for_each 是一个例外)。其find_if 的结果是类之一,而不是任何类型的值。传入的“lambda”也不是通常的 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();
    

    【讨论】:

    • 在我的示例中,ClassA、ClassB 和 ClassC 都是类类型。我已经能够让boost::mpl::for_each 解决另一个问题,所以我不认为我的困惑在于对类型的操作。我的错误是我在boost::mpl::find_if 中将仅编译时类型与运行时字符串混合在一起吗?也就是说,我的谓词是否必须只编译时?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-20
    • 1970-01-01
    • 2018-07-07
    • 2016-09-22
    相关资源
    最近更新 更多