decltype as a return type in class member function

后端 未结 3 1289
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 18:42

I got error compiling below code.

struct B{
    double operator()(){
        return 1.0;
    }
};

struct A {
    auto func() -> decltype(b())
    {
             


        
相关标签:
3条回答
  • 2020-12-01 19:18

    You can also get it to work like this:

    struct B
    {
        double operator()()
        {
            return 1.0;
        }
    };
    
    // my implementation does not have std::declval
    template < typename T > T&& declval();
    
    struct A
    {
        B b;
        auto func() -> decltype(declval<B>().operator()())
        {
            return b();
        }
    };
    

    edit: or since B is in scope already anyway no need for auto, -> decltype and declval

    struct A
    {
        B b;
        decltype(Q()()) func()
        {
            return b();
        }
    };
    
    0 讨论(0)
  • 2020-12-01 19:21

    Is it valid?

    Your last example is well-formed, while the first one is not (so GCC is correct).

    Paragraph 3.4.1/7 on unqualified name lookup specifies:

    A name used in the definition of a class X outside of a member function body, default argument, brace-or- equal-initializer of a non-static data member, or nested class definition shall be declared in one of the following ways:

    before its use in class X or be a member of a base class of X (10.2), or

    — [...]

    And what follows are other conditions that do not apply in your case.

    0 讨论(0)
  • 2020-12-01 19:33

    The definition of the class is processed it two passes: first the member declarations are collected, including function signatures, and then the bodies of definitions are parsed.

    The function body therefore has access to all member declarations, including subsequent ones, but the function prototype only sees preceding declarations.

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