Search code examples
c++c++11templateslvaluefunction-templates

How to force, value to be lvalue reference?


I want my function to take a lvalue reference and absolutely not a rvalue or temporary or whatever.

This is my function:

template<class T>
void foo(T& value) {}

// Imagine I have a class Foo
struct Foo
{ 
   int a;
   int b;
};

When I call foo(Foo{1, 2}), first, it compiles even if I asked for a lvalue reference, and second, it doesn't work because foo stores the address of the passed value, so I get garbage when I read it later.

How to force foo to take a lvalue reference?


Solution

  • First of all, the given code will not compile by default in GCC and Clang, only in MSVC with non-standard extensions.

    If you want to make sure that foo() does not accept an rvalue, just delete that overload:

    template<class T>
    void foo(T&& value) = delete;