Argument type deduction, references and rvalues

Posted by uj2 on Stack Overflow See other posts from Stack Overflow or by uj2
Published on 2011-01-02T13:23:11Z Indexed on 2011/01/02 13:54 UTC
Read the original article Hit count: 179

Consider the situation where a function template needs to forward an argument while keeping it's lvalue-ness in case it's a non-const lvalue, but is itself agnostic to what the argument actually is, as in:

template <typename T>
void target(T&) {
    cout << "non-const lvalue";
}

template <typename T>
void target(const T&) {
    cout << "const lvalue or rvalue";
}


template <typename T>
void forward(T& x) {
    target(x);
}

When x is an rvalue, instead of T being deduced to a constant type, it gives an error:

int x = 0;
const int y = 0;

forward(x); // T = int
forward(y); // T = const int
forward(0); // Hopefully, T = const int, but actually an error
forward<const int>(0); // Works, T = const int

It seems that for forward to handle rvalues (without calling for explicit template arguments) there needs to be an forward(const T&) overload, even though it's body would be an exact duplicate.

Is there any way to avoid this duplication?

© Stack Overflow or respective owner

Related posts about c++

Related posts about templates