Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a variable not an lvalue in C++?

#include <type_traits>

int main()
{    
    int n;
    n = 0;

    // failure!
    static_assert(std::is_lvalue_reference_v<decltype(n)>); 
}

n can be put on the left side, so it should be obviously an lvalue.

Why does the static_assert fail?

like image 627
xmllmx Avatar asked Oct 29 '25 14:10

xmllmx


1 Answers

decltype has special rules for id-expressions, deducing their type without regard to value category. If you want it to deduce a type based on the value category an id-expression normally has, you can surround the id-expression in parenthesis:

static_assert(std::is_lvalue_reference_v<decltype((n))>); 

(n) has the same type and value category as n in the type system, but isn't treated specially by decltype. Since the expression is an lvalue, the deduced type will be of an lvalue reference type.

like image 106
StoryTeller - Unslander Monica Avatar answered Oct 31 '25 05:10

StoryTeller - Unslander Monica