Cout template problem

Hey all,

I have this constructor:

template<class X, class T=point<X>>
class Circle: public shape

Now I need to know what is the type of X and print it !! ??
ofcourse every circle is constructed in main and type of circle is sent from there!.

Thank u
C++ doesn't have reflective abilities, meaning you cannot print the type of X.
You can use typeid for this purpose.

std::cout << typeid( X ).name() << std::endl;

However the output depends on the compiler implementation.

The other way is to use functions from <type_traits> as, for example, std::is_same
Last edited on
Isn't typeid() only for polymorphic types?
IIRC it works for anything, it just has a bit more utility for polymorphic types.
Well, I just thought about a possible solution: A macro like this one:

1
2
3
4
5
6
7
8
9
#define DECLARE_CIRCLE(X) typedef Circle<X, #X> Circle##X

//And modify the Circle template to accept a char*:
template<class X, const char *N, class T = point<X>>
class Circle : public Shape
{
    const char *_typeName = N;
    ...
};


Then the class is declared through the macro. If you type DECLARE_CIRCLE(int); you'll have a class called Circleint with a private field called _typeName pointing to the string "int".

Did not test it, but I think it works. Maybe this helps.
Topic archived. No new replies allowed.