Is it possible to print a variable's type in standard C++?

前端 未结 21 1909
南笙
南笙 2020-11-22 01:41

For example:

int a = 12;
cout << typeof(a) << endl;

Expected output:

int
21条回答
  •  离开以前
    2020-11-22 02:06

    Copying from this answer: https://stackoverflow.com/a/56766138/11502722

    I was able to get this somewhat working for C++ static_assert(). The wrinkle here is that static_assert() only accepts string literals; constexpr string_view will not work. You will need to accept extra text around the typename, but it works:

    template
    constexpr void assertIfTestFailed()
    {
    #ifdef __clang__
        static_assert(testFn(), "Test failed on this used type: " __PRETTY_FUNCTION__);
    #elif defined(__GNUC__)
        static_assert(testFn(), "Test failed on this used type: " __PRETTY_FUNCTION__);
    #elif defined(_MSC_VER)
        static_assert(testFn(), "Test failed on this used type: " __FUNCSIG__);
    #else
        static_assert(testFn(), "Test failed on this used type (see surrounding logged error for details).");
    #endif
        }
    }
    

    MSVC Output:

    error C2338: Test failed on this used type: void __cdecl assertIfTestFailed(void)
    ... continued trace of where the erroring code came from ...
    

提交回复
热议问题