Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving the type of auto in C++11 without executing the program

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?

like image 267
user1825464 Avatar asked Jun 26 '14 22:06

user1825464


People also ask

Does C++11 have 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.

Can the return type of a function be auto?

In C++14, you can just use auto as a return type.

What is Auto * C++?

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.

What is auto datatype?

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.


1 Answers

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).

like image 176
Shoe Avatar answered Oct 21 '22 17:10

Shoe