|
-
July 12th, 2012, 02:57 PM
#1
A question regarding template instantiation
Suppose I have a template class defined as,
Code:
template<class T>
class A
{
public:
void foo()
{
T* p = new T;
p->bar();
}
};
When I instantiate A, I either use A<B> or use A<C>. Here B and C is just two different types. B and C both define member function bar. My question is that in run time, is there any way I can detect whether p is of B or C? Thanks.
-
July 12th, 2012, 03:23 PM
#2
Re: A question regarding template instantiation
 Originally Posted by LarryChen
My question is that in run time, is there any way I can detect whether p is of B or C? Thanks.
The question I would like to ask you is why you need to know whether p is a B or a C at that point. If you need to know this, you should revisit your design. So let's say you could do this, what would you be doing with the code?
Code:
template<class T>
class A
{
public:
void foo()
{
T* p = new T;
if (it's a B)
p->bar();
else
if (it's a C)
do_something_else();
}
};
So you're drifting back into old-style 'C' type coding, defeating the whole purpose of a template. What happens if its a D, E, F object, all with bar() functions?
If you really are going to do something based on a different type in the template, then you need to specialize the template on that type. That is not a runtime concept -- template specialization occurs at compile time,
Regards,
Paul McKenzie
-
July 13th, 2012, 01:19 AM
#3
Re: A question regarding template instantiation
 Originally Posted by LarryChen
When I instantiate A, I either use A<B> or use A<C>.
You can use A<B>, A<C> or even A<int>, A<WhatEver>. However, in order to get your code compile, the "T" should have bar().
My question is that in run time, is there any way I can detect whether p is of B or C?
Depends, upon what you want to do (as Paul stated). If you provide more details, it can be helpful. Check boost type traits is_same for further details.
Last edited by Ejaz; July 13th, 2012 at 01:48 AM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|