C++ How to allow copy-list-initialization for a perfect forwarding function?

64 views Asked by At

Suppose I have a perfect forwarding function:

template <typename T>
void f(T&& t) { /* does something */ }

I have some types T that I want to allow Copy-list-initialization for, say they are std::pair<int, int> and std::tuple<int, int, int>:

f({1, 2}); // I want to do this
f({1, 2, 3}); // and I also want to do this

f(std::pair{1, 2}); // instead of this

I know that I have to have an overload of f(const std::pair<int, int>&) for this. How do I call f(T&&) inside f(const std::pair<int, int>&)?

void f(const std::pair<int, int>& p) {
    f(p); // How do I make this resolve to f(T&&)?
}
1

There are 1 answers

0
tearfur On

Found the answer.

void f(const std::pair<int, int>& p) {
    f<const std::pair<int, int>&>(p);
}

Edit: Or slightly better:

void f(const std::pair<int, int>& p) {
    f<decltype(p)>(p);
}