Question

Like std::reference_wrapper uses a pointer under the covers to store a "reference", I am trying to do something similar with the following code.

#include <type_traits>

struct Foo
{
    void* _ptr;

    template<typename T>
    Foo(T val,
        typename std::enable_if
            <
                std::is_reference<T>::value,
                void
            >::type* = nullptr)
        : _ptr(&val)
    { }
};

int main()
{
    int i = 0;
    int& l = i;

    Foo u2(l);

    return 0;
}

However, this fails to compile:

CXX main.cpp
main.cpp: In function ‘int main()’:
main.cpp:23:13: error: no matching function for call to ‘Foo::Foo(int&)’
main.cpp:23:13: note: candidates are:
main.cpp:8:5: note: template<class T> Foo::Foo(T, typename std::enable_if<std::is_reference<_Tp>::value, void>::type*)
main.cpp:8:5: note:   template argument deduction/substitution failed:
main.cpp: In substitution of ‘template<class T> Foo::Foo(T, typename std::enable_if<std::is_reference<_Tp>::value, void>::type*) [with T = int]’:
main.cpp:23:13:   required from here
main.cpp:8:5: error: no type named ‘type’ in ‘struct std::enable_if<false, void>’
main.cpp:3:8: note: constexpr Foo::Foo(const Foo&)
main.cpp:3:8: note:   no known conversion for argument 1 from ‘int’ to ‘const Foo&’
main.cpp:3:8: note: constexpr Foo::Foo(Foo&&)
main.cpp:3:8: note:   no known conversion for argument 1 from ‘int’ to ‘Foo&&’

How can I make the enable_if return true for reference parameters?

Was it helpful?

Solution

T in this case will never be deduced to be a reference type. In your construction of the object u2, the constructor template argument is deduced to be int.

While the type of the variable u2 is int&, when you use u2 in an expression, it is an lvalue expression of type int. An expression never has reference type.

Template argument deduction uses the types of the function arguments to deduce the template parameter types. Function arguments are expressions. Therefore, because no expression has reference type, a template argument will never be deduced to be a reference type.

[In C++11, if a function argument has type T&&, T may be deduced to the type T& if the argument is an lvalue. This mechanism enables perfect forwarding. That's not related to your scenario, though.]

In effect, in an expression, an object and a reference to that object are indistinguishable. A reference just allows you to give another name to the object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top