473,657 Members | 2,426 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

template specialization

Does anyone know if you can specialize a template function for
arguments that are pointers to a particular base class and not lose
the subclass type?

example:

template <class E>
void DeliverEvent(E *Event);

is a function that will receive an Event object, and then eventually
pass it to the proper destination. To avoid downcasting, any
destination will have a "ReceiveEve nt" function that is overloaded for
each specific Event class it is interested in.

There is a particular class of Events, call them "CallEvents ", which
require special processing before passing them along. So I want to
specialize the function as such:

template <>
void DeliverEvent(Ci rcuitEvent *Event);

But in doing it this way, the Event object becomes a base class
pointer, and I lose its specific type (and I would like to avoid
downcasting to regain it).

Is there a way to specialize the template function so that my template
argument keeps it type?

Thanks,
Eric Simon
Jul 22 '05 #1
4 4792
Hey Eric, I must be missing something here, hope I don't make a total
fool of myself ...
template <class E>
void DeliverEvent(E *Event);
template <>
void DeliverEvent(Ci rcuitEvent *Event);


Don't you need to specify the type in the specialization (hope I've
got this right...) ?
template <>
void DeliverEvent<Ci rcuitEvent>(Cir cuitEvent* Event);
------------

Second, if you're dealing with a class heirarchy, why do you need to
use templates here at all? Can't you just overload the function?
(pardon the silly question)
void DeliverEvent(Ev ent* e);
void DeliverEvent(Ci rcuitEvent* e);

Jeff
Jul 22 '05 #2
On 20 Nov 2003 15:32:44 -0800, pu*****@hotmail .com (Eric) wrote:
Does anyone know if you can specialize a template function for
arguments that are pointers to a particular base class and not lose
the subclass type?

example:

template <class E>
void DeliverEvent(E *Event);

is a function that will receive an Event object, and then eventually
pass it to the proper destination. To avoid downcasting, any
destination will have a "ReceiveEve nt" function that is overloaded for
each specific Event class it is interested in.

There is a particular class of Events, call them "CallEvents ", which
require special processing before passing them along. So I want to
specialize the function as such:

template <>
void DeliverEvent(Ci rcuitEvent *Event);

But in doing it this way, the Event object becomes a base class
pointer, and I lose its specific type (and I would like to avoid
downcasting to regain it).

Is there a way to specialize the template function so that my template
argument keeps it type?
Yes, but it's a bit complicated (first download boost from
www.boost.org).

Basically you don't specialize the template, but instead dispatch to a
particular implementation based on properties of the passed type. In
this case, your looking for SpecialEvent and classes derived from it.

#include <iostream>
#include <boost/type_traits.hpp >
using namespace boost;

struct Event
{
};

struct SpecialEvent
{
virtual ~SpecialEvent() {}

void non_virtual()
{
std::cout << "SpecialEvent:: non_virtual\n";
}
};

struct DerivedSpecialE vent: SpecialEvent
{
void non_virtual()
{
std::cout << "DerivedSpecial Event::non_virt ual\n";
}
};

template <bool>
struct DeliverEventImp l
{
template <class Event>
static void do_it(Event* event)
{
std::cout << "Non specialized\n";
}
};

template<>
struct DeliverEventImp l<true>
{
//SpecialEvent version
template <class Event>
static void do_it(Event* event)
{
event->non_virtual( );
}
};
template <class E>
void DeliverEvent(E* event)
{
DeliverEventImp l<
is_base_and_der ived<SpecialEve nt, E>::value
|| is_same<Special Event, E>::value::do_it(event) ;

}

int main()
{
Event e;
SpecialEvent se;
DerivedSpecialE vent dse;
DeliverEvent(&e );
DeliverEvent(&s e);
DeliverEvent(&d se);
}

Tom
Jul 22 '05 #3
je********@yaho o.com (Jeff) wrote in message news:<7b******* *************** ****@posting.go ogle.com>...
Hey Eric, I must be missing something here, hope I don't make a total
fool of myself ...
template <class E>
void DeliverEvent(E *Event);
template <>
void DeliverEvent(Ci rcuitEvent *Event);
Don't you need to specify the type in the specialization (hope I've
got this right...) ?
template <>
void DeliverEvent<Ci rcuitEvent>(Cir cuitEvent* Event);


Yes, you are right. My mistake.
------------

Second, if you're dealing with a class heirarchy, why do you need to
use templates here at all? Can't you just overload the function?
(pardon the silly question)
void DeliverEvent(Ev ent* e);
void DeliverEvent(Ci rcuitEvent* e);
The problem is that Event and Circuit Event are base classes. There
are several concrete classes that inherit from Event. Circuit Event
also inherits from Event, and in turn, has several concrete classes
inheriting from it. I use templates because I don't want to have to
downcast to regain the subclass type. I guess it's a very weak
hierarchy - the base class has very little functionality. Most of the
interesting stuff is specific to each subclass.

Thanks,
Eric

Jeff

Jul 22 '05 #4
> > Second, if you're dealing with a class heirarchy, why do you need to
use templates here at all? Can't you just overload the function?
(pardon the silly question)
void DeliverEvent(Ev ent* e);
void DeliverEvent(Ci rcuitEvent* e);


The problem is that Event and Circuit Event are base classes. There
are several concrete classes that inherit from Event. Circuit Event
also inherits from Event, and in turn, has several concrete classes
inheriting from it. I use templates because I don't want to have to
downcast to regain the subclass type.


I'm still puzzled as to why you need templates, though ... shouldn't
polymorphism do the trick? In Scott Meyers's "Effective C++, 2nd ed",
Item 41 says "Differenti ate between inheritance and templates" -- the
section is aimed at class templates, but can be generalized to
functions as well. The summary of the item, copied from the book, is
here:

- A template should be used to generate a collection of classes when
the type of the objects /*does not*/ affect the behaviour of the
class's functions.

- Inheritance should be used for a collection of classes when the type
of the objects /*does*/ affect the behaviour of the class's functions.

Since you're talking about changing the behaviour of a particular
function depending on the type of item passed to it, polymorphism (or,
in this case, function overloading) seems to be called for...

But perhaps I'm missing something. Can you boil your problem down to
a simple representation and post it? That way I (and others) might be
able to comment more appropriately on your problem (perhaps creating a
new thread in this group, and copying the messages from this thread to
the new post).

Jeff
Jul 22 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

17
6849
by: Paul MG | last post by:
Hi Template partial specialization always seems like a fairly straightforward concept - until I try to do it :). I am trying to implement the input sequence type (from Stroustrup section 18.3.1, 'Iseq'). I want the version for containers that he gives, but also to provide a specialization for construction from a pair<It,It> (eg because that is returned by equal_range()).
2
2534
by: SainTiss | last post by:
Hi, If you've got a template class with lots of methods, and then you've got a type which works with the template, except for one method... What you need to do there is specialize the template for your type. However, this requires you to copy the whole template, and change the method, which leads to code duplication... If there's only 1 template parameter, one can specialize the method
8
7670
by: Agent Mulder | last post by:
Hi group, I have a problem with partial template specialization. In the code below I have a template struct Music with one method, play(), and three kinds of music, Jazz, Funk and Bach. When I specialize Music<Bach>, I expect that the original play() method is available in the specialization, but it is not. How can I fix this? -X
2
5770
by: Jeff | last post by:
/* -------------------------------------------------------------------------- Hello, I was experimenting with class templates and specializing member functions and came across a simple problem which I can't figure out. I have a simple class C with 2 template member objects, and a function print() that prints the value of these objects. I defined a specialization of print() for C<string, char> which is called correctly. Then I wanted...
6
2010
by: Dave | last post by:
Hello all, Consider this function template definition: template<typename T> void foo(T) {} If foo is never called, this template will never be instantiated. Now consider this explicit instantiation of foo:
4
1959
by: TT \(Tom Tempelaere\) | last post by:
Comeau compiler complains (too few arguments for class template "B") at line *** #include <memory> template<typename T, size_t n> struct A {}; template<typename T, size_t n> struct B;
9
2764
by: Marek Vondrak | last post by:
Hello. I have written the following program and am curious why it prints "1" "2". What are the exact effects of explicitly providing function template parameters at the call? Is the second assign() function really a specialization of the first assign() or is it an assign() overload? Thank you. -- Marek
2
2486
by: Thomas Kowalski | last post by:
Hi, I would like to write a template class Polygon<VertexTypthere vertex typ can be eigther a pointer or a value typ. It has an attribute: std::vector<VertexTypvertices; And a methode: VertexValueTyp& vertex(int i); that dereferences vertices internally in case VertexTyp is a pointer
2
7690
by: Barry | last post by:
The following code compiles with VC8 but fails to compiles with Comeau online, I locate the standard here: An explicit specialization of any of the following:
6
2607
by: abir | last post by:
i have a template as shown template<typename Sclass Indexer{}; i want to have a specialization for std::vector both const & non const version. template<typename T,typename Aclass Indexer<std::vector<T,A {} matches only with nonconst version. anyway to match it for both? and get if it is const or nonconst? Actually i want 2 specialization, one for std::vector<T,Aconst & non const other for std::deque<T,Aconst & non const.
0
8315
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8829
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8508
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8608
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7341
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4323
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2733
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1962
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1627
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.