简体   繁体   English

在C++中展开模板class列表

[英]Expand template class list in C++

I have a template function to do sth with type T我有一个模板 function 可以用类型 T 做某事

template <class T>
void EmplaceProcessor()
{
    T* pProcessor = new T();
    m_vItemProcessors.emplace_back(pProcessor);
}

If I want to implement a lot of types to emplace to the vector, just sth like:如果我想实现很多类型来放置到向量中,就像这样:

template<class...A> 
void EmplaceAllProcessor()
{
    const int size = sizeof...(A);
    for (int i = 0; i < size; ++i)
    {
        EmplaceProcessor<A[i]>();     //how to expand it?????
    }
}

and I want to call EmplaceAllProcessor<P1, P2, P3>();我想打电话给 EmplaceAllProcessor<P1, P2, P3>(); to emplace all types of processor安置所有类型的处理器

I want to call EmplaceAllProcessor<P1, P2, P3>();我想调用 EmplaceAllProcessor<P1, P2, P3>(); to emplace all types of processor, How can it be?安放各类处理器,怎么可能呢?

In C++11, you can use a dummy array initialization trick:在 C++11 中,您可以使用虚拟数组初始化技巧:

template<class... A> 
void EmplaceAllProcessor() {
    int dummy[] = {0, (EmplaceProcessor<A>(), 0)...};
    (void)dummy;
}

A comma operator expression is used to invoke EmplaceProcessor<A>() for each type in the pack A... , in order (the order of evaluation of arguments in a braced list is fixed by their order in that list per [dcl.init.list/4] ). 逗号运算符表达式用于按顺序为包A...中的每种类型调用EmplaceProcessor<A>() (大括号列表中 arguments 的评估顺序由它们在该列表中的顺序固定[dcl.初始化列表/4] )。 The first 0 is needed to support an empty pack and (void)dummy;需要第一个0来支持空包和(void)dummy; suppresses an unused variable warning.抑制未使用的变量警告。

If I want to return a value, for example: bool EmplaceAllProcessor() to return whether it is succeeded and bool EmplaceAllProcessor() to tell if all the EmplaceProcessor work succeeded, how can it be?如果我想返回一个值,比如: bool EmplaceAllProcessor()返回是否成功, bool EmplaceAllProcessor()判断所有EmplaceProcessor工作是否成功,怎么可能呢?

If you don't need short circuiting, it's a simple extension of the above approach:如果不需要短路,这是上述方法的简单扩展:

template<class... A> 
bool EmplaceAllProcessor() {
    bool res[] = {true, EmplaceProcessor<A>()...};
    return std::all_of(std::begin(res), std::end(res), [](bool b) { return b; });
}

If short circuiting is needed, another small trick might be used:如果需要短路,可以使用另一个小技巧:

template<class... A> 
bool EmplaceAllProcessor() {
    bool res = true;
    bool dummy[] = {true, (res = res && EmplaceProcessor<A>())...};
    (void)dummy;
    return res;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM