473,769 Members | 5,900 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Elegant way of making template arguments dependent on user input?

Hey everybody,
I got into serious trouble with template programming. I have a class
which uses three template arguments, say
template<typena me Atype, typename Btype, typename Ctype>
class some_class {
};
and I want to make the values of these template arguments dependent on
the input of the program as shown by the following pseudocode:
if (input_for_Atyp e == "a")
firsttype := first_A;
else if (input_for_Atyp e == "b")
firsttype := second_A;
//...

if (input_for_Btyp e == "1")
secondtype := first_B;
else if (input_for_Btyp e == "2")
secondtype := second_B;
//...

// analogous for Ctype

// instanciate correct version of "some_class "
some_class<firs ttype, secondtype, thirdtypeinstan ce_of_class;

// Begin doing stuff with the class
instance_of_cla ss.do_something ();
//...
// End
I hope you get the idea.

The number of choices for each template argument is limited of course,
so a canonical solution would be to write out each possible combination
of the template arguments. This is really ugly, since in my case there
are already 24 possible combinations (2*4*3) for the template arguments,
and there will most likely be more in the future. Also the code would be
redundant, as the part between "Begin doing stuff" and "end" is always
the same for each of the combinations.

My question is whether there is a more elegant way to solve my problem.

I have already tried to do the following. For each of the template
arguments write a function which decides (dependant on the input) the
type of its related template, like this:
template<typena me Atype, typename Btype, typename Ctype>
inline void run() {
some_class<Atyp e, BType, Ctypeinstance_o f_class();
// do the stuff... code is only written once!
}

template<typena me Atype, typename Btype>
inline void choose_C() {
if (input_for_Ctyp e == 1)
run<Atype, Btype, first_C>();
else if (input_for_Ctyp e == 2)
run<Atype, Btype, second_C>();
// ...
}

template<typena me Atype>
inline void choose_B() {
if (input_for_Btyp e == 1)
choose_C<Atype, first_B>();
else if (input_for_Btyp e == 2)
choose_C<Atype, second_B>();
//...
}

inline void choose_A() {
if (input_for_Atyp e == 1)
choose_B<first_ A>();
else
choose_B<second _A>();
}

int main() {
choose_A();
}
Unfortunately this won't work in my case, since the value of the Atype
template also depends on "input_for_Ctyp e". In fact, the method choose_A
looks like this:
inline void choose_A() {
if (input_for_Atyp e == 1 || input_for_Ctype == 1)
choose_B<first_ A>();
else
choose_B<second _A>();
}
Now, it is crucial for input_for_Ctype == 1 to use first_A as the Atype,
since it defines some member variables which aren't available in
second_A. Unfortunately my C++ compiler seems to compile the code in the
run method for Atype = second_A and Ctype = first_C as well, though this
path is never taken in the program. This is leading to errors that
second_A won't have the requested members. Declaring all functions
inline as shown above didn't help.
I hope this wasn't too much at once, but the situation seems to be
rather complex. If there are any questions to the problem just feel free
to ask them and I will try to explain it in more detail.
Is there any solution for this or is it just impossible in C++? Of
course an alternative would be to do it with class inheritance and
virtual methods, but this is no option, since performance is most
important (I'm testing algorithms on huge datasets, taking hours of time
already). "Googling" on this problem didn't really reveal anything of use.
Greets and thanks in advance,
Thomas

PS: Maybe this is of use:

# gcc -v
Using built-in specs.
Target: x86_64-suse-linux
Configured with: ../configure --enable-threads=posix --prefix=/usr
--with-local-prefix=/usr/local --infodir=/usr/share/info
--mandir=/usr/share/man --libdir=/usr/lib64 --libexecdir=/usr/lib64
--enable-languages=c,c++ ,objc,fortran,j ava,ada --enable-checking=releas e
--with-gxx-include-dir=/usr/include/c++/4.1.0 --enable-ssp
--disable-libssp --enable-java-awt=gtk --enable-gtk-cairo
--disable-libjava-multilib --with-slibdir=/lib64 --with-system-zlib
--enable-shared --enable-__cxa_atexit --enable-libstdcxx-allocator=new
--without-system-libunwind --with-cpu=generic --host=x86_64-suse-linux
Thread model: posix
gcc version 4.1.0 (SUSE Linux)
# uname -a
Linux compute6 2.6.16.13-4-smp #1 SMP Wed May 3 04:53:23 UTC 2006 x86_64
x86_64 x86_64 GNU/Linux
Oct 9 '07 #1
3 1980
Thomas Pajor wrote:
....
Is there any solution for this or is it just impossible in C++? Of
course an alternative would be to do it with class inheritance and
virtual methods, but this is no option, since performance is most
important (I'm testing algorithms on huge datasets, taking hours of time
already). "Googling" on this problem didn't really reveal anything of use.
You really need to check to see if performance is an issue before you go
spending an effort on it.

If it is user input, you need to instantiate every case possible of your
template. To make it selectable, a base class or a pointer to a
function with the same signature is needed, I prefer an abstract base class.

The most extensible system (no switch or if's) is a generalized factory
system like the one in Austria C++.

Once all classes have been registered with the factory you can simply

Base * p = at::FactoryRegi ster< Base, Key >( Key( A, B, C ) )();

Any way you look at it, you need to instantiate all the possible types
you care about.
Oct 9 '07 #2
On 2007-10-09 23:12, Thomas Pajor wrote:
Hey everybody,
I got into serious trouble with template programming. I have a class
which uses three template arguments, say
template<typena me Atype, typename Btype, typename Ctype>
class some_class {
};
and I want to make the values of these template arguments dependent on
the input of the program as shown by the following pseudocode:
Templates are a compile-time construct. You can not use any information
that is not known at compile-time when instantiating them.

--
Erik Wikström
Oct 9 '07 #3
Erik Wikström wrote:
Templates are a compile-time construct. You can not use any information
that is not known at compile-time when instantiating them.
I'm well aware of this, but I thought the compiler could use the limited
amount of available choices for each template argument to generate all
neccessary versions of the class and instanciate the correct one
depending on the user input.

Basically I was looking for a way to shorten code like this
if (input_choice_A == 1) {
if (input_choice_B == 1) {
some_class<firs tA,firstBinstan ce();
// redundant code
} else {
some_class<firs tA,secondBinsta nce();
// redundant code
}
} else {
if (input_choice_B == 1) {
some_class<seco ndA,firstBinsta nce();
// redundant code
} else {
some_class<seco ndA,secondBinst ance();
// redundant code
}
}
Of course, instead of inserting the redundant code each time, you could
write a templated function like this:
template<typena me Atype, typename Btype>
void run(some_class< Atype, Btype&instance) {
// Redundant code here only once
}
So it seems to be technically possible to make template values dependent
on user input. But - and this is what really concerns me - I'd need to
define each combination of template arguments manually, which is a LOT
in my case. It would be much shorter (and easier maintainable) if I
could define them in a way as illustrated here
if (input_choice_A == 1)
typedef firstA first_argument; // I know this won't be visible from
outside the if construct
else
typedef secondA first_argument;

if (input_choice_B == 1)
typedef firstB second_argument ;
else
typedef secondB second_argument ;
And then just instanciate the class with
some_class<firs t_argument, second_argument instance();
The advantage of such a technique becomes more and more obvious the more
combinations for the template arguments there are.
Regards,
Thomas
Oct 10 '07 #4

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

Similar topics

0
2768
by: |-|erc | last post by:
Hi! Small challenge for you. The index.php uses this file and calls layout(). Take a look at www.chatty.net this file draws the chat login box on the right. I traced the CHAT button it submits and goes to the index file again, I can't figure out how it opens the chatroom. I want to get it to skip the login box and go straight to the room, with user name "guest" or "" or whatever but I'll add a field to type the name in the chat room....
2
1476
by: Alexander Stippler | last post by:
Hi, I'm not quite sure if I have to use the keyword template in a situation, where my compiler enforces it, though I think it is not neccessary. My question is: Who is wrong with respect to the standard - the compiler or I? template <typename T> struct A { template <typename C>
31
3534
by: nikola | last post by:
Hi all, I was working with a simple function template to find the min of two values. But since I would like the two values to be different (type) I dont know what kind of value (type) it will return. I tried to write something like this: template <class Type1, class Type2, class Type3> Type3 findMin(Type1 x, Type2 y){ return (x < y) ? x : y;
10
1836
by: philchen1978 | last post by:
Hi, I can compile the code below with GCC 3.4.2, because function g is a "dependent name". template<class T> void f1(T t) { g(t); }
14
2905
by: Bart Samwel | last post by:
Hi everybody, I would really like some help explaining this apparent discrepancy, because I really don't get it. Here is the snippet: void foo(int&); void foo(int const&); template<typename T>
34
3706
by: Asfand Yar Qazi | last post by:
Hi, I'm creating a library where several classes are intertwined rather tightly. I'm thinking of making them all use pimpls, so that these circular dependancies can be avoided easily, and I'm thinking of making all these pimpl class declarations public. Reasoning is that since only the code within the ..cc file will need to ever access them, why protect them in ways that would make access to them more difficult and obfuscated? What...
8
1950
by: mattias.nissler | last post by:
Hi! Here is a problem I ran into at work. The following example doesn't compile on gcc-4.1: struct cons_end {}; template<typename U,typename Vstruct cons { U elem; V tail;
0
165
by: James Kanze | last post by:
On May 16, 9:34 am, Paavo Helde <nob...@ebi.eewrote:
2
2027
by: puzzlecracker | last post by:
See it a lot but haven't learn the difference between this two in the context of template. Would someone explain it please? Thanks
0
9586
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10043
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
9990
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
8869
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
7406
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
6672
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
5298
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
5446
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2814
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.