473,782 Members | 2,487 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Deciding execution path based on template parameters?


I was trying something with templates in C++, can't figure out if it is
possible.

Can I check in a function what template parameter was passed, and then
decide what to do?

for example...

I have two simple types:

struct x {int a, b, c};
struct y {int x};

A template class is defined with
template<class T>

then in one of the member functions, I want to do

if(T==x) { do something with a, b and c}
if(T==y) { do something with x}

(These ifs need to be resolved at compile time, else the code wont
compile.)

Something similar can be done through template specialization, but I
was hoping if such if/else is possible.

I can do if(typeid(T ) == typeid(x))

but this is resolved at run time... I want something which gets
resolved at compile time. To avoid the performance hit.
I can think of a work around....

template<int t_id, class T>

and then in code...

if(t_id==x_id) { do stuff for x}
if(t_id==y_id) { do stuff for y}

(here x_id and y_id are constants)
Only problem is that now t_id and T essentially mean the same thing, so
its kinda redundant to specify both. But this should work
Templates can have if else on value parametres which get solved at
compile time, I was just hoping if it can do that with type parameters
too.

Technically this seems to be possible. What will be the best option in
this case, any alternates you can suggest.
Sachin Garg [India]
www.sachingarg.com | www.c10n.info

Sep 4 '06 #1
3 1941
In article <11************ ********@m79g20 00cwm.googlegro ups.com>,
sc*****@gmail.c om says...
>
I was trying something with templates in C++, can't figure out if it is
possible.

Can I check in a function what template parameter was passed, and then
decide what to do?

for example...

I have two simple types:

struct x {int a, b, c};
struct y {int x};

A template class is defined with
template<class T>

then in one of the member functions, I want to do

if(T==x) { do something with a, b and c}
if(T==y) { do something with x}
This is done somewhat differently. You start by writing a template that
works for types in general (though in some cases, the general version is
never intended to be used, and may intentionally cause an error so it
_can't_ be used).

Then you write a specialization for the types that receive special
treatement:

template <class T>
class XYZ {
// whatever
};

template <>
class XYZ<x{
// do something with a, b, c
};

template <>
class XYZ<y{
// do something with x
};

This is handled by compile time -- but it does NOT (directly) support
writing only _part_ of the template in a specialized fashion -- you have
to reproduce the specialized template in general. If you want to
specialize only part, you need to split that part out into a separate
template of its own.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Sep 4 '06 #2

Jerry Coffin wrote:
In article <11************ ********@m79g20 00cwm.googlegro ups.com>,
sc*****@gmail.c om says...

I was trying something with templates in C++, can't figure out if it is
possible.

Can I check in a function what template parameter was passed, and then
decide what to do?

for example...

I have two simple types:

struct x {int a, b, c};
struct y {int x};

A template class is defined with
template<class T>

then in one of the member functions, I want to do

if(T==x) { do something with a, b and c}
if(T==y) { do something with x}

This is done somewhat differently. You start by writing a template that
works for types in general (though in some cases, the general version is
never intended to be used, and may intentionally cause an error so it
_can't_ be used).

Then you write a specialization for the types that receive special
treatement:

template <class T>
class XYZ {
// whatever
};

template <>
class XYZ<x{
// do something with a, b, c
};

template <>
class XYZ<y{
// do something with x
};

This is handled by compile time -- but it does NOT (directly) support
writing only _part_ of the template in a specialized fashion -- you have
to reproduce the specialized template in general. If you want to
specialize only part, you need to split that part out into a separate
template of its own.
My goal behind using templates here is to avoid duplicated code :-)

I guess I will try using the t_id approach I mentioned and see how it
goes.

Thanks,
Sachin Garg [India]
www.sachingarg.com | www.c10n.info

Sep 4 '06 #3
In article <11************ *********@i3g20 00cwc.googlegro ups.com>,
sc*****@gmail.c om says...

[ ... ]
My goal behind using templates here is to avoid duplicated code :-)
Right -- if you only have a few things in a few places that depend on
the type, you can still use templates, but factor those few bits into
their own functions (or functors) and supply that as a template
parameter:

struct x { int a, b, c; };
strut y { int x; };

struct x_spec {
void operator()(x const &xx) {
// do something with x
}
};

struct y_spec {
void operator()(y const &yy) {
// do something with y
}
};

template <class T, class special>
class whatever {
T t;
public:
void member1() {
special()(t); // code specialized for one type
}

void member2() {
// code for either type
}
};

This depends, however, on being able to factor the specialized behavior
into a relatively small number of specialized functions. If you have
lots of different type-dependencies spread throughout the code, it's
probably not going to work very well -- but then again, that starts to
sound like what you have may not have enough commonality to really gain
a lot from code sharing in any case. In a case like that, instead of a
class template, you might be better off with a few function templates to
provide a common code base for the things that really are the same
across the types.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Sep 4 '06 #4

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

Similar topics

1
3076
by: karoshi | last post by:
Hello, I want to gain insight into the access and running of scripts by the php engine on my production box. Most scripts are executed via cronjobs and they invoke a lot of other php scripts. I can backtrace these files, but a lot of other scripts are run by our users from the command line and I want to know if it possible to instruct the engine to log the names of these script files.
5
4159
by: mas | last post by:
I have a Stored Procedure (SP) that creates the data required for a report that I show on a web page. The SP does all the work and just returns back a results set that I dump in an ASP.NET DataGrid. The SP takes a product area and a start and end date as parameters. Here are the basics of the SP. 1. Create temp table to store report results, all columns are created that will be needed at this point. 2. Select products and general...
4
2285
by: Erik Wikström | last post by:
In school (no I will not ask you to do my schoolwork for me) we talked about policy-based design and got an assignment where we got the a code- fragment from a stack-implementation. The idea with the code was that if, when its destructor was called, it still contained any elements it would run 'delete' on them if they were pointers and do nothing if they were not. Our assignment was to reimplement the stack using policies so that the...
7
1564
by: Michael Kennedy [UB] | last post by:
Hi, I am back with more bug reports from Visual Studio.NET 2003's C++ compiler (unmanaged). Consider the following method: --------------------------------------------- __forceinline bool CReplayBase::ReplayFillBuffer() { CFile* pFile = NULL;
6
2811
by: rincewind | last post by:
Hi, can anybody summarise all options for partial template specialization, for all kind of parameters (type, nontype, template)? I *think* I understand options for partial specialization on type parameters - in place of a template argument one can construct arbitrary valid C++ type declaration, more or less like in "typedef" statement. What about nontype parameters? Am I right that you cannot partially
1
3499
by: SomebodyElse | last post by:
Hi. Apologies if this has been asked here before - I've searched & searched but can't find anything. It's probably my serach parameters, but I'm having trouble even describing it to a search engine! I'm sure this is a very simple problem, with straighforward solution. It certainly is in classic asp/ado, but I'm finally learning this .NET business. I like it, but can't get my head around some concepts. Anyway....
17
5098
by: romixnews | last post by:
Hi, I'm facing the problem of analyzing a memory allocation dynamic and object creation dynamics of a very big C++ application with a goal of optimizing its performance and eventually also identifying memory leaks. The application in question is the Mozilla Web Browser. I also have had similar tasks before in the compiler construction area. And it is easy to come up with many more examples, where such kind of statistics can be very...
4
3105
by: Dan Krantz | last post by:
I have the following template to ensure that a given number (val) falls into a range (between vmin & vmax): template<typename T> T ForceNumericRange( const T& val, const T& vmin, const T& vmax) { T retVal = val; if ( retVal < vmin ) retVal = vmin;
8
11521
by: moondaddy | last post by:
I'm posting code for a user control ( FunctionConnectorSelector) below which has 3 content controls in it. each content control uses a style from a resource dictionary merged into the app.xaml file. each control has a border with another style, and each border has a unique path inside of it. I need to dynamically add these content controls using c# at runtime and am having trouble referencing the styles and adding the path into the...
0
10311
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...
0
10146
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10080
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
9942
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
8967
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...
1
7492
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6733
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5378
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5509
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.