Home > front end >  Is it possible to identify the datatype of an object at compile time in C ?
Is it possible to identify the datatype of an object at compile time in C ?

Time:11-16

It is possible to identify the datatype at runtime using RTTI, but how do we do it at compile time, is it even possible ?

CodePudding user response:

decltype gets the underlying type at compile time. The standard defines many utilities, called traits, that performs checks on types.


E.g. combining these traits with if constexpr allows compile time branching. A basic example:

template<typename T>
void fun(T object) {
    if constexpr (std::is_same_v<decltype(object), std::string>) {
        std::cout << '"' << object << "\"\n";
    }
    if constexpr (std::is_unsigned_v<decltype(object)>) {
        std::cout << "unsigned\n";
    }
    else if constexpr (std::is_pointer_v<decltype(object)>) {
        std::cout << *object << '\n';
    }
    else if constexpr (std::is_base_of_v<foo, decltype(object)>) {
        std::cout << "derived from foo\n";
    }
}

CodePudding user response:

C supports Template Meta programming. Meta programming means compile time programming where we can work with types rather than values. This is achieved mainly with the trickery of Template specialization

For example, following code can be used to query a type, say, to identify whether a particular type is a pointer or not. All of it happens at compile time


template<class T>
struct isPointer{
static bool value = false;
}

template<class T> // Template specialization 
struct isPointer<T*>{
static bool value = true;
}
  • Related