Question

At the definition of a function template, the instantiations of template parameters are in general unknown. Type traits can be used to obtain some information at compile-time. For example, here is a trivial application of is_pointer:

template <typename T>
void foo(T p) { cout << is_pointer<T>::value << endl; }

My question is this: Is there ever a situation, in a non-template function, where traits-like, compile-time functions could provide useful information?

Was it helpful?

Solution

Yes:

#include <iostream>
#include <limits>

int main()
{
    std::cout << "Max value of an int on your platform is "
              << std::numeric_limits<int>::max() << "\n";
}

This is the first example that came to mind. I'm sure there are many others. More generally, it allows compile-time "lookup" keyed on type. Obviously, in a non-template situation, the same could be achieved with macro definitions (INT_MAX, etc.).

OTHER TIPS

Unless to inspect compile time info about basic type, like the max and min for integral types or whatever.

The real benefit for type traits is to aid template meta programming, either by addding control flow with sfinae or to produce better error when an incorrect type is used.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top