Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::is_same gives strange result in using C++17 structured binding

I have some simple C++ code (g++ compiler) in which std::is_same trait gives (in my opinion) a weird (unexpected) result: static_assert below:

class Person {
public:
    const std::string _given_name;
    const std::string _surname;
    std::string _nickname;
    Person(const std::string& given_name, const std::string& surname, const std::string& nickname)
        : _given_name(given_name), _surname(surname), _nickname(nickname) {
    }
};

Person p("Donald", "Duck", "?");
auto& [gn, sn, nn] = p; // C++17 binding
nn = "Blondie";
std::cout << p._nickname << std::endl; // 'Blondie'
static_assert(std::is_same<decltype(nn), std::string&>::value); // Fails!
static_assert(std::is_same<decltype(nn), std::string>::value);  // Succeeds!
like image 504
Bab Avatar asked Dec 13 '19 10:12

Bab


1 Answers

From cppreference about decltype:

If the argument is an unparenthesized id-expression naming a structured binding, then decltype yields the referenced type (described in the specification of the structured binding declaration).

In your case in fact decltype is the culprit, not the structured binding itself (or I guess they are in cahoots). So instead you want decltype((nn)) for your static_assert to succeed.

like image 82
DeiDei Avatar answered Nov 04 '22 19:11

DeiDei