Search code examples
c++c++11externdecltype

Can the type of a previously defined extern variable be inferred without using decltype


// header

int extern has_a_type; // (1) extern declaration

// implementation

decltype(has_a_type)   // (2) unnecessarily verbose type inference code
has_a_type;            // (3) definition

I understand that I can use decltype so I do not actually have to type (or even know, to some extent) the type of a extern declared (1) variable when defining (3) (and possibly initializing) it. However decltype forces me to write out the name of the variable (potentially fully qualified and long) twice (2).

How can I avoid writing it twice? Something along the lines of auto has_a_type; (which does, of course, not work).


Solution

  • You can't - facetiously because nobody has convinced the standards committee as to the merit of being able to write

    int extern has_a_type;
    auto has_a_type;
    

    despite its tractability. It might turn out that

    decltype(auto) has_a_type;
    

    would be necessary in order to disambiguate type deduction from initialisers and then, unfortuantely, we're not too far removed from the repetitious decltype(has_a_type) that's already available.