Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 925
Jasper Koning Avatar asked Oct 27 '22 01:10

Jasper Koning


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;
}
like image 82
CoralK Avatar answered Nov 15 '22 09:11

CoralK