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

后端 未结 4 1664
别跟我提以往
别跟我提以往 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 21:23

    You can, but you have to declare it static and const:

    struct Timer {
        static const auto start = 0;
    };
    

    A working example in Coliru.

    With this limitation, you therefore cannot have start as a non-static member, and cannot have different values in different objects.

    If you want different types of start for different objects, better have your class as a template

    template
    struct Timer {
        T start;
    };
    

    If you want to deduce the type of T, you can make a factory-like function that does the type deduction.

    template
    Timer::type> MakeTimer(T&& startVal) {   // Forwards the parameter
       return Timer::type>{std::forward(startVal)};
    }
    

    Live example.

提交回复
热议问题