What is an unnamed type in C++?

后端 未结 2 638
独厮守ぢ
独厮守ぢ 2021-01-11 11:17

As part of my toilet reading on the C++ Standard ANSI ISO IEC 14882 2003, I came across the following:

14.3.1.2: A local type, a type with no linkage,

相关标签:
2条回答
  • 2021-01-11 11:30

    "Unnamed type" really means "unnamed enumeration or class type" [for more information, see the comments to this answer]. An enumeration or class type doesn't have to have a name. For example:

    struct { int i; } x; // x is of a type with no name
    

    You could try to use an unnamed type as a template argument through argument deduction:

    template <typename T> void f(T) { }
    
    struct { int i; } x;
    f(x); // would call f<[unnamed-type]>() and is invalid in C++03
    

    Note that this restriction has been lifted in C++0x, so this will be valid (you'll also be able to use local types as type template parameters). In C++0x, you could also use decltype to "name" an unnamed type:

    template <typename T> void g() { }
    
    struct { int i; } x;
    f<decltype(x)>(); // valid in C++0x (decltype doesn't exist in C++03)
    
    0 讨论(0)
  • 2021-01-11 11:31

    Think about the following code:

    template <typename T>
    void foo(const T&) {}
    
    struct {
      int x;
    } y;
    foo(y);
    

    That includes an unnamed type. Note that the rule is different in C++0x.

    0 讨论(0)
提交回复
热议问题