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

后端 未结 5 1543
悲&欢浪女
悲&欢浪女 2021-01-11 10:10

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 f

5条回答
  •  感动是毒
    2021-01-11 10:59

    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 struct S;
    
    int main() {
        auto x = ...;
        S();
    }
    

    Live demo

    which will produce an error message in the form:

    error: implicit instantiation of undefined template 'S' (clang++)
    error: invalid use of incomplete type 'struct S' (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).

提交回复
热议问题