런타임동안에 C++컴파일러를 쓰고 있는지 알아내는 코드가 필요합니다
조회수 1024회
#ifdef
를 쓰는거 말고
C컴파일러를 쓸때는 0, C++컴파일러를 쓸때는 1을 return하는 함수를 짤 수 있나요?
예를들면
임시 코드
int isCPP()
{
return sizeof(char) == sizeof 'c';
}
//아니면
int isCPP()
{
typedef int T;
{
struct T
{
int a[2];
};
return sizeof(T) == sizeof(struct T);
}
}
대충 이런 함수였으면 합니다.
그리고 또 비슷하게 C++03이랑 C++11을 감지하는 함수도 짤 수 있는지 궁금합니다.
bool isCpp11()
{
//???
}
1 답변
-
C와 C++을 구분하는 함수
1. ::을 써서 enum에 접근
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); }
2. new keyword의 차이를 이용
struct a { }; struct b { a a1, a2; }; struct c : a { static b constexpr (a()); }; bool isCpp0x() { return (sizeof c::a()) == sizeof(b); }
3. string literal의 char* 변환을 이용
bool isCpp0xImpl(...) { return true; } bool isCpp0xImpl(char*) { return false; } bool isCpp0x() { return isCpp0xImpl(""); }
4. int&& 변환 차이를 이용
C++0x에서는 int&&으로 변환되고, C++03에서는 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); }
5. Standard Library
C++0x에 std::basic_ios는
operator void*
가 없음을 이용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); }
댓글 입력