Corentin M
Corentin M

Reputation: 107

How to assign a value using std::get on a tuple?

I need to use a tuple in my code to be able to conveniently store three data with different type in a vector. That is to say, I have something like this :

std::vector<std::tuple<sf::Time, sf::Time, std::function<void()> > > m_timedFunctions;

Where the first sf::Time represent how often should we call the std::function, and the second sf::Time represent the timestamp of the last call to the function. The goal is to be able to call a function at regular interval automatically.

I have no problem creating and inserting a tuple into the vector, but for some reason when I try to modify the second sf::Time using std::get<1>(u), it just does not happen. I can read the data perfectly, but in no way it lets me modify it.

Here's how I create the tuple :

void addTimedFunction(sf::Time freq, std::function<void()> f)
{
    auto a = std::make_tuple(freq, sf::seconds(0), f);
    m_timedFunctions.push_back(a);
}

but later if I do something like this : std::get<1>(a) = sf::seconds(10); (where a is a tuple from m_timedFunctions that I get with a ranged-base for), the second member stays at 0.

The whole part of my code where I'm modifying it :

void MainWindow::processTimedFunctions()
{
    for(auto a : m_timedFunction)
    {
        sf::Time elapsed = m_clock.getElapsedTime();
        sf::Time lastExec = std::get<1>(a);

        sf::Time diff = elapsed - lastExec;

        if( diff.asMilliseconds() >= std::get<0>(a).asMilliseconds())
        {
            std::get<1>(a) = sf::seconds(10); //   m_clock.getElapsedTime();    // Update the last execution time
            std::get<2>(a)();             // Call the linked function
        }
    }
}

How can I effectively modify it ?

Upvotes: 4

Views: 2295

Answers (1)

interjay
interjay

Reputation: 110145

This creates a copy of the elements you're iterating over:

for(auto a : m_timedFunction)

Any changes you make to a will not affect the container.

To get a reference instead of a copy, use:

for(auto &a : m_timedFunction)

Upvotes: 3

Related Questions