I have some C++11 code using the auto
inferred type that I have to convert to C++98. How would I go about converting the code, substituting in the actual type for all instances of auto
?
C++11 introduces the keyword auto as a new type specifier. auto acts as a placeholder for a type to be deduced from the initializer expression of a variable. With auto type deduction enabled, you no longer need to specify a type while declaring a variable.
In C++14, you can just use auto as a return type.
The auto keyword is a simple way to declare a variable that has a complicated type. For example, you can use auto to declare a variable where the initialization expression involves templates, pointers to functions, or pointers to members.
1) auto keyword: The auto keyword specifies that the type of the variable that is being declared will be automatically deducted from its initializer. In the case of functions, if their return type is auto then that will be evaluated by return type expression at runtime.
It is going to be a PITA, but you can declare an incomplete struct template accepting a single type parameter.
Given the variable x
you want to know the type of, you can use the struct with decltype(x)
and that will lead to a compiler error that will show you the inferred type.
For example:
template<class Type> struct S;
int main() {
auto x = ...;
S<decltype(x)>();
}
Live demo
which will produce an error message in the form:
error: implicit instantiation of undefined template 'S<X>' (clang++)
error: invalid use of incomplete type 'struct S<X>' (g++)
with X
being the inferred type. In this particular case the type is int
.
Trivia: This has been recommended by Scott Meyer in one of the recent NDC 2014's videos (I don't remember which one).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With