Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if a type exists in C++ [duplicate]

I'd need a template which can be called like this:

int x = type_exists< std::vector<int> >::value;

This should set x to 1 if #include <vector> was present (either explicitly or transitively) earlier in the source, otherwise it should set x to 0.

Is it possible to do it in C++? I'm using GCC, so GCC extensions are also fine.

It's also OK to change the call syntax a bit.

It's not OK to run the C++ compiler twice: first just to figure out if we get a compile error.

like image 515
pts Avatar asked Dec 15 '13 11:12

pts


2 Answers

This is not what you are looking for, but it's as close as you can get to a type_exists trait:

template<class T> struct Void { typedef void type; };

template<class T, class U = void>
struct type_exists { enum { value = 0 }; };

template<class T>
struct type_exists<T, typename Void<T>::type> { enum { value = 1 }; };

Apparently, it works:

static_assert(type_exists<int>::value, "int is not defined");
static_assert(type_exists<SomeNonexistingType>::value, "expected compile-time error");

This does exactly what it is supposed to do. Tested with GCC 5.4.0.

like image 100
ManuelAtWork Avatar answered Nov 14 '22 18:11

ManuelAtWork


This is not possible, I'm afraid. If we were to use a non defined identifier we would get a compilation error, leading to this code:

int x = type_exists< std::vector<int> >::value;

not to even compile.

Also, the standard doesn't specify any preprocessor directive to be declared within the header file (which is implementation defined instead) for the standard library, therefore you won't be able to detect it even with preprocessor macros.

like image 37
Shoe Avatar answered Nov 14 '22 19:11

Shoe