0 Replies - 1949 Views - Last Post: 12 February 2012 - 11:23 AM

#1 ishkabible   User is offline

  • spelling expret
  • member icon





Reputation: 1747
  • View blog
  • Posts: 5,898
  • Joined: 03-August 09

checking types for convertibility and inheritance in C++

Posted 12 February 2012 - 11:23 AM

Description: simply use the macros as presentedthese few macros are based on the ideas and code presented in "Modern C++" by Andrei Alexandrescu. You can compare types for convertibility and inheritance and optionally reject equal types.
#include <iostream>
#include <ios>

#define IS_SUPER_CLASS(T, U)
	(is_convertible<const T*, const U*>::value &&
	!is_convertible<const T*, const void*>::same_type)

#define IS_SUPER_CLASS_STRICT(T, U)
	(IS_SUPER_CLASS(T,U) &&
	!is_convertible<const T, const U>::same_type)

#define IS_CONVERTIBLE(T, U)
	(is_convertible<const T, const U>::value)

#define IS_CONVERTIBLE_STRICT(T, U)
	(is_convertible<const T, const U>::value &&
	!is_convertible<const T, const U>::same_type)

template<class T, class U>
class is_convertible {
private:
	template<int x>
	class dummy {
		int blah[x];
	};
	static dummy<1> test(U);
	static dummy<2> test(...);
public:
	static const bool value = sizeof(test(T())) == sizeof(dummy<1>);
	static const bool same_type = false;
};

template<class T>
class is_convertible<T, T> {
public:
	static const bool value = true;
	static const bool same_type = true;
};


class foo {};
class bar : public foo {};

int main() {
	std::cout<<std::boolalpha;
    std::cout<<IS_CONVERTIBLE(char, int)<<'n';
    std::cout<<IS_CONVERTIBLE(float, char*)<<'n';

	std::cout<<IS_CONVERTIBLE_STRICT(float, double)<<'n';
    std::cout<<IS_CONVERTIBLE_STRICT(char, char)<<'n';

	//foo is super class of foo
    std::cout<<IS_SUPER_CLASS(bar, foo)<<'n';
    std::cout<<IS_SUPER_CLASS(foo, foo)<<'n';

	std::cout<<IS_SUPER_CLASS_STRICT(bar, foo)<<'n';
    std::cout<<IS_SUPER_CLASS_STRICT(foo, foo)<<'n';
    return 0;
}



Is This A Good Question/Topic? 0
  • +

Page 1 of 1