代码之家  ›  专栏  ›  技术社区  ›  AdyAdy

通过对象访问类子类型

  •  0
  • AdyAdy  · 技术社区  · 6 年前
    class Foo{
    
    public:
        struct Bar{};
    
    };
    
    ...
    
    Foo foo;
    
    foo.Bar bar; //error
    

    struct Foo::Bar . 在这里,我当然可以命名子类 Foo::Bar 如果我想但是如果 foo

    *编辑:为了清楚起见,我想创建一个Foo::Bar类型的对象,而不必写 Foo:: .

    4 回复  |  直到 6 年前
        1
  •  2
  •   jsantander    6 年前

    在前面的类似回答之后,使用 decltype specifier :

    class Foo{
    
    public:
        struct Bar{};
    
    };
    
    int main() {
        Foo foo;
        decltype(foo)::Bar bar;
        const Foor foofoo;
        decltype(foofoo)::Bar barbar;
    }
    

    #include <type_traits>
    ...
    
    void fref(const Foo &foo) {
       typename std::remove_reference<decltype(foo)>::type::Bar bar;
    }
    
    void fpointer(Foo *foo) {
       typename std::remove_reference<decltype(*foo)>::type::Bar bar;
    }
    
        2
  •  1
  •   Aconcagua    6 年前

    [F]oo 具有很长的嵌套模板类型[…]

    好的,假设你有:

    class Foo
    {
        template <typename T>
        class SomeVeryLongAndInconvenientName;
    };
    

    您可以使用特定类型为定义别名:

    using ShorterName = Foo::SomeVeryLongAndInconvenientName<SomeType>;
    

    template <typename T>
    using ShorterName = Foo::SomeVeryLongAndInconvenientName<T>;
    
        3
  •  0
  •   P.W    6 年前

    如果您有 struct Bar class Foo decltype :

    class Foo{
    public:
        struct Bar{};
        Bar f_bar; 
    
    };
    
    Foo foo;
    decltype(foo.f_bar) bar;
    
        4
  •  0
  •   R Sahu    6 年前

    如果 foo

    您可以使用以下策略。

    1. 声明一个返回类型的成员函数。没有必要定义它,除非它是有用的。

    2. 使用 decltype 让编译器从成员函数派生类型。


    这是您发布的代码的更新版本。

    class Foo {
    
       public:
          struct Bar{};
    
          // Just the declaration is sufficient.
          Bar b() const;
    
    };
    
    
    int main()
    {
       Foo foo;
       decltype(foo.b()) bar;
    }
    
    推荐文章