在参数包的每个值上应用函数并检查返回值

时间:2018-11-21 11:51:17

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

拥有这段工作代码:

template < class... Objects >
static void callNotifyOnPointerObjects ( Objects&&... objects )
{
    int arr[] = { 0, ( static_cast< void > ( objects->Notify () ), 0 )... };
    static_cast< void > ( arr );
}

objects->Notify()返回值为bool

如何将objects->Notify()执行时返回的布尔值放入bool数组中,并检查所有值是否都是true

template < class... Objects >
static bool callNotifyOnPointerObjects ( Objects&&... objects )
{
    // Put in this array return values from objects->Notify () execution
    bool rc [sizeof...(objects)] = {false};
    int arr[] = { 0, ( static_cast< void > ( objects->Notify () ), 0 )... };
    static_cast< void > ( arr );
    // check if all values in rc == true and return true or false
    // return result;
}

1 个答案:

答案 0 :(得分:3)

struct foo {
    bool Notify() const { return /* something */; }
};

template<typename... Objects>
bool callNotifyOnPointerObjects(Objects&&... objects)
{
    bool rc[]{ objects->Notify() ... };
    for (auto const &c : rc)
        if(!c) return false
    return true;
}

或者,按照@ n.m的建议使用std::all_of()而不是for循环。在评论中:

#include <iterator>
#include <algorithm>

// ...

template<typename... Objects>
bool callNotifyOnPointerObjects(Objects&&... objects)
{
    bool rc[]{ objects->Notify() ... };
    return std::all_of(std::begin(rc), std::end(rc), [](bool b){ return b; });
}

但是,这样做可能更有效

template<typename... Objects>
bool callNotifyOnPointerObjects(Objects&&... objects)
{
    return (objects->Notify() + ...) == sizeof...(objects);
}