c++fold-expression

What is wrong with my lambda in fold expression


I'm trying to form std::vector of smart pointers to objects in the following way:

#include <iostream>
#include <vector>
#include <memory>

template<typename... Args>
std::vector<std::shared_ptr<int>> createSourceVector(Args... args)
{
    std::vector<std::shared_ptr<int>> result;
    (
        [&]() {
            result.push_back(std::make_shared<int>(args));
        },
        ...);
    return result;
}

int main()
{
    auto sources = createSourceVector(1,2,3);
    std::cout << sources.size() << '\n'; // 0

    return 0;
}

However, the result vector is always empty. It seems that fold expression doesn't see properly my result variable. How to fix it?


Solution

  • The lambda that does the push_back is not being invoked (Clang gives a warning about this https://godbolt.org/z/zzhfT993G).

    You need to add an () after the lambda:

    (
      [&]() {
        result.push_back(std::make_shared<int>(args));
      }(),  // <-- add () here
    ...);
    

    However, you don't need a lambda at all. You can just write the fold expression like this:

    (result.push_back(std::make_shared<int>(args)), ...);
    

    You can also initialize the returned vector directly in a braced-initializer:

    return {std::make_shared<int>(args)...};
    

    If the return type is deduced with auto, you can still write:

    return std::vector<std::shared_ptr<int>>{
             std::make_shared<int>(args)...
           };