简体   繁体   English

使用 decltype 作为构造函数参数

[英]using decltype for constructor parameters

I'm curious as to why the order of member declaration in this case is an issue:我很好奇为什么在这种情况下成员声明的顺序是一个问题:

class A
{
public:
    A(decltype(b_) b)
        : b_{b}
    {}

private:
    std::function<void(int, std::string, float)> b_;
};

// error: ‘b_’ was not declared in this scope

while just changing the declaration order works:虽然只是更改声明顺序有效:

class A
{
    std::function<void(int, std::string, float)> b_;

public:
    A(decltype(b_) b)
        : b_{b}
    {}
};

Since both gcc and Clang handle it in the same manner I'd say that it's not a bug but I still find it confusing.由于 gcc 和 Clang 都以相同的方式处理它,我会说这不是一个错误,但我仍然觉得它令人困惑。

This has to do with the completed-class context .这与完成的类上下文有关 A class is considered completed, only in:一个班级被认为是完成的,只有在:

  • function body ( [dcl.fct.def.general] ),函数体( [dcl.fct.def.general] ),

  • default argument,默认参数,

  • noexcept-specifier, or noexcept 说明符,或

  • default member initializer默认成员初始值设定项

and the parmeter list of a member function is not a part of that.并且成员函数的参数列表不是其中的一部分。 That means that any type you use needs to already be known (seen) by the compiler.这意味着您使用的任何类型都需要被编译器知道(看到)。 In

class A
{
public:
    A(decltype(b_) b) <- class not complete here
        : b_{b}       <- class is complete here since the mem-initializer list is part of [dcl.fct.def.general]
    {}                <-/

private:
    std::function<void(int, std::string, float)> b_;
};

b_ has not been seen yet, so you get a compiler error. b_还没有被看到,所以你会得到一个编译器错误。 With

class A
{
    std::function<void(int, std::string, float)> b_;

public:
    A(decltype(b_) b)
        : b_{b}
    {}
};

b_ has been seen, so there is no error using it later on in the class. b_已经被看到,所以以后在课堂上使用它没有错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM