根据可变类型做出决定
Make decision depending on variadic types
我知道我已经把标题弄得尽可能模糊了,但示例有望设定目标。
我有一个 Base
class 和 Derived
class 的家庭(classy 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::variant
检查 hold_alternative
或像这样的 smth,但我只有类型没有值。更复杂的是,我的编译器受 C++14 支持的限制。
有人可以为此提出一些 tiny/elegant 解决方案吗?
And to complicate the matters, my compiler is limited with C++14 support.
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
}
}
}
我知道我已经把标题弄得尽可能模糊了,但示例有望设定目标。
我有一个 Base
class 和 Derived
class 的家庭(classy 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::variant
检查 hold_alternative
或像这样的 smth,但我只有类型没有值。更复杂的是,我的编译器受 C++14 支持的限制。
有人可以为此提出一些 tiny/elegant 解决方案吗?
And to complicate the matters, my compiler is limited with C++14 support.
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
}
}
}