Is it possible to have an “auto” member variable?

后端 未结 4 1662
别跟我提以往
别跟我提以往 2021-01-03 20:54

For example I wanted to have a variable of type auto because I\'m not sure what type it will be.

When I try to declare it in class/struct declaration it

4条回答
  •  难免孤独
    2021-01-03 20:58

    This is what the C++ draft standard has to say about using auto for member variables, in section 7.1.6.4 auto specifier paragraph 4:

    The auto type-specifier can also be used in declaring a variable in the condition of a selection statement (6.4) or an iteration statement (6.5), in the type-specifier-seq in the new-type-id or type-id of a new-expression (5.3.4), in a for-range-declaration, and in declaring a static data member with a brace-or-equal-initializer that appears within the member-specification of a class definition (9.4.2).

    Since it must be initialized this also means that it must be const. So something like the following will work:

    struct Timer
    {
      const static int start = 1;
    }; 
    

    I don't think that gets you too much though. Using template as Mark suggests or now that I think about it some more maybe you just need a variant type. In that case you should check out Boost.Variant or Boost.Any.

提交回复
热议问题