Distinguish between pass-by-value and pass-by-reference in a function template

Viewed 88

Is there a way to let the compiler distinguish whether the passed variable is a reference or not, without explicitly specifying it using e.g. <int &>? The following example displays '1', whereas I expected a '2':

template <typename Type>
void fun(Type)
{
    cout << 1 << '\n';
}

template <typename Type>
void fun(Type &)
{
    cout << 2 << '\n';
}

int main()
{
    int x = 0;
    int &ref = x;
    fun(ref);
}

I also tried to use std::ref, but I don't get it to work.

1 Answers
template <typename Type, typename = std::enable_if_t<!std::is_reference<Type>::value>>
void fun(Type)
{
    std::cout << 1 << '\n';
}

template <typename Type, typename = std::enable_if_t<std::is_reference<Type>::value>>
void fun(Type &)
{
    std::cout << 2 << '\n';
}

int main() {

    int x = 0;
    int &ref = x;
    fun<int&>(ref); // Call the one that you want, and don't leave the compiler decide which one you meant

    return EXIT_SUCCESS;
}
Related