【问题标题】:Make decision depending on variadic types根据可变参数类型做出决定
【发布时间】:2021-02-23 23:11:36
【问题描述】:

我知道我已经使标题尽可能模糊,但示例有望设定目标。

我有一个 Base 班级和 Derived 班级的家庭(优雅的 OOD,仅此而已)。
此外,我有一个采用可变参数模板的函数,我想根据这些模板做出决定。

template<typename... Ts>
void do_smth(std::vector<std::shared_ptr<Base>>& vec) {
    for (auto&& ptr: vec) {
        if the dynamic type of ptr is one of Ts.. then do smth.
    }
}

我打算这样调用函数:

do_smth<Derived1, Derived2>(vec);

我知道我可以将Ts... 转发到std::varianthold_alternative 或类似这样的检查,但我只有类型而不是值。更复杂的是,我的编译器受限于 C++14 支持。
有人可以建议一些小/优雅的解决方案吗?

【问题讨论】:

  • 如果Base是基类,使用虚函数有什么问题?
  • @Phil1970 因为该算法用于数学模型,如果一个模型的实现可能是正确的,那么另一个模型可能是错误的。所以需要在这一层做出决定。
  • (dynamic_cast&lt;T *&gt;(ptr) != NULL || ...) 这样的 C++17 折叠表达式应该可以解决问题,因此您所要做的就是使用帮助模板在 C++14 中实现折叠表达式。几乎任何折叠表达式都可以手动实现,一次一步。一定有很多这样的例子,就在这附近……
  • 也许一个更真实的例子会有所帮助?你真的需要shared_ptr吗?
  • 您真的想根据类型参数或对象的运行时类型进行分派吗?在当前代码中,这些是不相关的。

标签: c++ c++11 templates c++14 variadic-templates


【解决方案1】:

更复杂的是,我的编译器受限于 C++14 支持。

C++14 ...所以你必须模拟模板折叠...

下面的内容呢?

template<typename... Ts>
void do_smth (std::vector<std::shared_ptr<Base>>& vec) {

    using unused = bool[];

    for ( auto&& ptr: vec)
     {
       bool b { false };

       (void)unused { b, (b = b || (dynamic_cast<Ts*>(ptr) != nullptr))... };

       if ( b )
        { 
          // ptr is in Ts... list
        }
       else
        { 
          // ptr isn't in Ts... list
        }
    }
}

【讨论】:

    猜你喜欢
    • 2014-10-20
    • 1970-01-01
    • 2020-12-26
    • 2012-04-07
    • 2018-04-09
    • 2013-12-16
    • 1970-01-01
    • 2011-07-22
    • 1970-01-01
    相关资源
    最近更新 更多