How to determine the type of expression?

Sometimes expressed expressions appear in the code. For example, heavy use of the Boost library attracts these expressions. If I want the type of typedefthis expression, I need to write its type. Is there a way to find out this type at compile time ( change: or runtime)? Perhaps Boost offers related functionality. I would like to use it as

#pragma message (...expression...)

EDIT: If there is a problem with detecting the type of compilation time, then a determination of the type of runtime is also detected. For example, a function like the following would match

template <typename T> std::string detectExpressionType(T t);
+3
source share
2 answers

++ 03 :

template<typename T>
void foo(T x)
{
    // Now you have the type of the expression.
}

int main()
{
    foo(1.0f * 2.0f);
}

#pragma message (...expression...), #pragma - . .

+2

- . , ( gcc).

#include <iostream>
#include <iostream>
#include <typeinfo>
#include <cxxabi.h>

template <typename T> struct DebugType;
template <typename T>
inline void debug_type() {
    DebugType<T>();
}
template <typename T>
inline void debug_type(const T&) {
    DebugType<T>();
}

std::string demangle(const std::string& source_name)
{
    std::string result;
    size_t size = 4096;
    // __cxa_demangle may realloc()
    char* name = static_cast<char*>(malloc(size));
    try {
        int status;
        char* demangle = abi::__cxa_demangle(source_name.c_str(), name, &size, &status);
        if(demangle) result = demangle;
        else result = source_name;
    }
    catch(...) {}
    free(name);
    return result;
}

template <typename T>
inline void log_type() {
    std::clog << demangle(typeid(T).name()) << '\n';
}

template <typename T>
inline void log_type(const T&) {
    std::clog << demangle(typeid(T).name()) << '\n';
}

int main()  {
    // error: incomplete type ‘DebugType<int>’ used in nested name specifier
    // debug_type<int>();
    log_type<int>();

    // // error: invalid use of incomplete type ‘struct DebugType<std::basic_istream<char> >
    // debug_type(std::cin);
    log_type(std::cin);
    return 0;

}
+1

All Articles