CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Jul 2005
    Posts
    1,030

    Thumbs up 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.

  2. #2
    Join Date
    Apr 1999
    Posts
    27,449

    Re: A question regarding template instantiation

    Quote Originally Posted by LarryChen View Post
    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

  3. #3
    Ejaz's Avatar
    Ejaz is offline Elite Member Power Poster
    Join Date
    Jul 2002
    Location
    Lahore, Pakistan
    Posts
    4,211

    Re: A question regarding template instantiation

    Quote Originally Posted by LarryChen View Post
    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
  •  





Click Here to Expand Forum to Full Width

Featured