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;
};
No. Each constructor could have its own initializer for
start
, so there could be no consistent type to use.If you do have a usable expression, you can use that:
You can, but you have to declare it
static
andconst
: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 templateIf you want to deduce the type of
T
, you can make a factory-like function that does the type deduction.Live example.
Indirectly, provided that you don't reference a member of the class.
This can also now be achieved through deduction guides, these were introduced in C++17 and have recently (finally) support in VC++ has been added (clang and GCC already had it).
https://en.cppreference.com/w/cpp/language/class_template_argument_deduction
For example:
https://godbolt.org/z/LyL7UW
This can be used to deduce class member types in a similar manner to auto. Although the member variables need to be Dependant somehow on the constructor arguments.
This is what the C++ draft standard has to say about using
auto
for member variables, in section7.1.6.4 auto specifier
paragraph4
:Since it must be initialized this also means that it must be
const
. So something like the following will work: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
orBoost.Any
.