'Accepting std::chrono::duration of any representation/period

I want a function to accept a duration in whatever units makes sense to the caller.

For example:

transition->after(chrono::seconds(3));
transition->after(chrono::milliseconds(500));
transition->after(chrono::hours(1));

What would a valid signature for this after function look like? Can I avoid making it a templated function?



Solution 1:[1]

Since c++17 we could use std::variant.

void after(std::variant<std::chrono::minutes, std::chrono::seconds> dt)

Inside the after function you can use std::visit to avoid code duplication. In the following example we add the given duration to "3 seconds":

void after(std::variant<std::chrono::minutes, std::chrono::seconds> dt) {
    std::chrono::seconds secs{3};
    std::visit([&secs](auto v)
                   { secs += v; }, dt);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Adelhart