Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have an "auto" member variable?

Tags:

c++

struct

auto

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's giving me this error:

Cannot deduce auto type. Initializer required

Is there a way around it?

struct Timer {      auto start;  }; 
like image 766
Oleksiy Avatar asked Aug 13 '13 02:08

Oleksiy


People also ask

How do you declare an auto variable?

To use the auto keyword, use it instead of a type to declare a variable, and specify an initialization expression. In addition, you can modify the auto keyword by using specifiers and declarators such as const , volatile , pointer ( * ), reference ( & ), and rvalue reference ( && ).

What is a member variable C++?

In object-oriented programming, a member variable (sometimes called a member field) is a variable that is associated with a specific object, and accessible for all its methods (member functions).

How do you access member variables?

Use the member-access operator ( . ) between the object variable name and the member name. If the member is Shared, you do not need a variable to access it.


1 Answers

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<typename T> 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<typename T> Timer<typename std::decay<T>::type> MakeTimer(T&& startVal) {   // Forwards the parameter    return Timer<typename std::decay<T>::type>{std::forward<T>(startVal)}; } 

Live example.

like image 106
Mark Garcia Avatar answered Sep 26 '22 03:09

Mark Garcia