0

I get the following error when using for_each on a vector of objects that inherit from an interface:

error: no matching member function for call to 'push_back'
note: candidate function not viable: 'this' argument has type 'const std::vector<std::shared_ptr<const Runner>>', but method is not marked const
note: candidate function not viable: 'this' argument has type 'const std::vector<std::shared_ptr<const Runner>>', but method is not marked const

My code from "manage.cpp" that throws this error:

std::vector<std::shared_ptr<const Runner>> Manage24h::getNextRunners(const std::string & teamName)
{
    std::vector<std::shared_ptr<const Runner>> candidates = getTeamCandidates(teamName);
    std::vector<std::shared_ptr<const Runner>> runners = {};
    //These work fine
    //runners.push_back(std::make_shared<Runner>("test",0,0));
    //runners.push_back(strategies.at(0)->getNextRunner(teamName, candidates));
    std::for_each(strategies.begin(), strategies.end(),
                  [candidates, teamName, runners](std::shared_ptr<Strategy> current)
    {
        //Error
        runners.push_back(current->getNextRunner(teamName, candidates));
    });
    return runners;
}

"strategies" are defined in my "manage.h"

private:
  std::vector<std::shared_ptr<Strategy>> strategies;

The compiler tells me my consts are wrong somewhere so I tried making making my entire vector const, making Runner const and making the entire method const. But that can't be it. The error seems to only appear when inside a for look or inside the std::for_each I am using. Might this be a problem with the way std::vector works itself?

vatsk
  • 36
  • 5
  • 1
    TL;DR - by default, objects captured by value in lambda are `const`. You need to mark is as `mutable` to modify them. But, it doesn't really seem reasonable to modify a copy, did you perhaps want to capture `runners` by reference? `[candidates, teamName, &runners]...` (and maybe capture the other vectors by reference too, to avoid copying) – Yksisarvinen Jan 20 '22 at 00:48
  • Yes, `mutable` solved my issue. I did want to capture by reference I forgot about my & thank you. – vatsk Jan 20 '22 at 01:05

0 Answers0