I need a code to find out if I'm using the C++ compiler during runtime

Asked 1 years ago, Updated 1 years ago, 125 views

Not using #ifdef Can you make a function that returns 0 when using C compiler and 1 when using C++ compiler? For example,

int isCPP()
{
    return sizeof(char) == sizeof 'c';
}

//or

int isCPP()
{
    typedef int T;
    {
       struct T 
       {
           int a[2];
       };
       return sizeof(T) == sizeof(struct T);
    }
}

I want it to be roughly this function.

And similarly, I wonder if we can plot a function that detects C++03 and C++11.

bool isCpp11()
{ 
    //???
} 

c++11 c c++ language-detection

2022-09-22 10:55

1 Answers

template<int> struct int_ { };

template<typename T> bool isCpp0xImpl(int_<T::X>*) { return true; }
template<typename T> bool isCpp0xImpl(...) { return false; }

enum A { X };
bool isCpp0x() {
  return isCpp0xImpl<A>(0);
}
struct a { };
struct b { a a1, a2; };

struct c : a {
  static b constexpr (a());
};

bool isCpp0x() {
  return (sizeof c::a()) == sizeof(b);
}
bool isCpp0xImpl(...) { return true; }
bool isCpp0xImpl(char*) { return false; }

bool isCpp0x() { return isCpp0xImpl(""); }

Convert to int&&& on C++03, convert to logical-and&&

struct Y { bool x1, x2; };

struct A {
  operator int();
  template<typename T> operator T();
  bool operator+();
} } a;

Y operator+(bool, A);

bool isCpp0x() {
  return sizeof(&A::operator int&& +a) == sizeof(Y);
}

Use that std::basic_ios does not have operator void* in C++0x

struct E { E(std::ostream &) { } };

template<typename T>
bool isCpp0xImpl(E, T) { return true; }
bool isCpp0xImpl(void*, int) { return false; }

bool isCpp0x() {
  return isCpp0xImpl(std::cout, 0);
}


2022-09-22 10:55

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.