Home > Blockchain >  Can't use std::apply on std::array
Can't use std::apply on std::array

Time:04-28

I am trying to apply a lambda to the elements of an std::array.

    std::array<int, 4> fixIndices = {1, 60, 127, 187};

    std::apply(
        [](int id) {
            std::cout << id;
        },
        fixIndices);

However, this simple code doesn't compile

/usr/lib/gcc/x86_64-pc-linux-gnu/10.3.0/include/c  /tuple:1727:27: error: no matching function for call to ‘__invoke(****)::<lambda(int)>, int&, int&, int&, int&)’
 1727 |       return std::__invoke(std::forward<_Fn>(__f),
      |              ~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~
 1728 |       std::get<_Idx>(std::forward<_Tuple>(__t))...);

What am I missing?

CodePudding user response:

std::apply is to call a callable with parameters given as a tuple. For example you can call some

auto f = [](int a,double b,char c) {}

with a std::tuple<int,double,char>. Note that std::array is tuple-like, ie you could use your array to call a callable that expects 4 parameters.

However, here you do not need std::apply. You can use a loop:

std::array<int, 4> fixIndices = {1, 60, 127, 187};
auto f = [](int id) { std::cout << id;};
for (const auto& id : fixIndices) f(id);

Or closer to your code via for_each:

std::for_each(fixIndices.begin(),fixIndices.end(), [](int id) { std::cout << id; });

CodePudding user response:

std::apply forwards the arguments contained in the tuple(-like) to the callable f, so your lambda should be

std::array<int, 4> fixIndices = {1, 60, 127, 187};
std::apply(
  [](auto... ids) {
     ((std::cout << ids << " "), ...);
  }, 
  fixIndices);

But for std::array, if you want to iterate over its elements, a range-based for loop is an easier option.

  • Related