Is it possible to replace "auto" with its deduced type, automatically, in C++?

251 views Asked by At

I've got a project I've been wrestling with for a while, which is almost ready for submission; but there have been a few previous coders who have contributed. Their code is great, but it doesn't satisfy the lint for the project this class is going to be submitted to; so, I'm spending some time cleaning it up.

One of the things this project forbids is the auto keyword. This is understandable, as a lot of people contribute to it, and they aren't all the most experienced so much as enthusiastic; so being explicit is a good thing.

There are quite a few autos in here. I remember that g++ -E would give me a file after the preprocessor was run, and it occurs to me that there's probably a way to do something similar with type specifiers.

Failing that, I'm using Qt Creator on a Linux box, which might also have a feature (kind of like "replace symbol under cursor") which I don't know about yet.

Is there anything that will allow me to automatically replace auto with its deduced type name, in a C++ file?

1

There are 1 answers

1
Jan Schultke On BEST ANSWER

No, this is not possible in general, for multiple reasons.

Firstly, there are cases where auto refers to unnamed types, such as closure types of lambdas, etc.

struct {
    int data;
} stuff;

auto s = stuff{}; // What exactly is auto here, decltype(stuff) ?

auto l = []{}; // What exactly is auto here?
               // decltype([]{}) is not the same type,
               // and the closure type has no name.
               // ... should we auto-generate a typedef?

But even if you always had a usable type, how exactly should it be formatted?

// What exactly is auto here?
//  - std::uint8_t
//  - ::std::uint8_t
//  - uint8_t
//  - unsigned char
//  - unsigned __char
auto c = get_uint8();

// What exactly is auto here?
//  - std::string
//  - std::basic_string<char>
//  - std::basic_string<char, std::allocator<char>>
//  - std::__cxx11::basic_string<char, std::__cxx11::allocator<char>>
auto str = get_std_string();

Knowing which type to display to the user is an extremely difficult problem in C++. IDEs often have special cases to deal with this. For example, CLion may display std::basic_string<char> as string, but this is not an automated transformation.