473,566 Members | 3,255 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Variable to take type of templated class with variable template parameter

Hi,

I have a class depending on a template parameter:

template<int n>
class MyClass {
};

I want the template parameter to be chosen according to a variable,
e.g.

switch (method) {
case 1:
pointer = new MyClass<1>;
break;

case 2:
pointer = new MyClass<2>;
break;

The question is: what type should 'pointer' be?

The only thing that occurs to me is to inherit MyClass from a non-
templated abstract base class:
class BaseClass {
};

template<int n>
class MyClass : public BaseClass {
};

and then define
BaseClass* pointer;

This seems to work, but it requires me to define dummy pure virtual
versions in BaseClass of all the methods in MyClass, which seems like
something that should be able to happen automatically.

Is there a simpler / better solution to this problem?

[The other question is how to make the switch statement automatic, but
that I guess one does with some kind of factory method?]

Thanks and best wishes,
David.

Oct 29 '07 #1
4 2355
On Oct 29, 8:08 am, David Sanders <dpsand...@gmai l.comwrote:
I have a class depending on a template parameter:
template<int n>
class MyClass {
};
I want the template parameter to be chosen according to a variable,
e.g.
switch (method) {
case 1:
pointer = new MyClass<1>;
break;
case 2:
pointer = new MyClass<2>;
break;
The question is: what type should 'pointer' be?
The only thing that occurs to me is to inherit MyClass from a non-
templated abstract base class:
class BaseClass {
};
template<int n>
class MyClass : public BaseClass {
};
and then define
BaseClass* pointer;
This seems to work,
It's also about the only thing that will work. Different
instantiations of MyClass are unrelated classes; you have to
explicitly relate them.
but it requires me to define dummy pure virtual versions in
BaseClass of all the methods in MyClass, which seems like
something that should be able to happen automatically.
Not really. What should this "implicitly defined" base class
look like if there are specializations of your template?
Templates and runtime polymorphism are two very different
things. If you want runtime polymorphism, you must follow the
rules of runtime polymorphism (even if you use templates in the
implementation of the derived types).

The basic reason for this is that runtime polymorphism takes
place in a different environment than template instantiation.
Templates can get away with duck typing because if you
instantiate over a type which doesn't meet the contract, the
compiler will complain, and the error doesn't go any further.
Use duck typing a runtime (a la Smalltalk or Lisp), and you risk
type errors at runtime---require a common base class and
explicit derivation, and the compiler can catch most of these
errors.
Is there a simpler / better solution to this problem?
[The other question is how to make the switch statement
automatic, but that I guess one does with some kind of factory
method?]
More or less (although I usually use factory objects). Just put
the address of the function/object in a map, indexed by the key.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Oct 29 '07 #2
David Sanders wrote:
Hi,

I have a class depending on a template parameter:
...
Is there a simpler / better solution to this problem?
No, there isn't. Different instantiation of template classes are not
related anyhow, so the correct way to link them is in letting them
derive from a single base class. And, the virtual functions are
unavoidable if you want polymorphic behaviour.
[The other question is how to make the switch statement automatic, but
that I guess one does with some kind of factory method?]
The switch part has to appear somewhere (in the factory, possibly),
since the template argument has to be resolved at compile-time. However,
depending on your specific problem you can rely on some class
auto-registration mechanism.
Thanks and best wishes,
David.
Best regards,

Zeppe

Oct 29 '07 #3
On Oct 29, 10:08 am, David Sanders <dpsand...@gmai l.comwrote:
Hi,

I have a class depending on a template parameter:

template<int n>
class MyClass {

};

I want the template parameter to be chosen according to a variable,
e.g.

switch (method) {
case 1:
pointer = new MyClass<1>;
break;

case 2:
pointer = new MyClass<2>;
break;

The question is: what type should 'pointer' be?

The only thing that occurs to me is to inherit MyClass from a non-
templated abstract base class:

class BaseClass {

};

template<int n>
class MyClass : public BaseClass {

};

and then define
BaseClass* pointer;

This seems to work, but it requires me to define dummy pure virtual
versions in BaseClass of all the methods in MyClass, which seems like
something that should be able to happen automatically.

Is there a simpler / better solution to this problem?

[The other question is how to make the switch statement automatic, but
that I guess one does with some kind of factory method?]

Thanks and best wishes,
David.
void * pointer;/*you will be responsible for type of the object*/

if 'pointer' is not of a polymorphic type you will be in trouble ,so I
think this is really bad.

regards,
FM.

regards,
FM.

Oct 29 '07 #4
On Oct 29, 3:36 am, Zeppe
<ze...@remove.a ll.this.long.co mment.yahoo.itw rote:
David Sanders wrote:
Hi,
I have a class depending on a template parameter:

...
Is there a simpler / better solution to this problem?

No, there isn't. Different instantiation of template classes are not
related anyhow, so the correct way to link them is in letting them
derive from a single base class. And, the virtual functions are
unavoidable if you want polymorphic behaviour.
[The other question is how to make the switch statement automatic, but
that I guess one does with some kind of factory method?]

The switch part has to appear somewhere (in the factory, possibly),
since the template argument has to be resolved at compile-time. However,
depending on your specific problem you can rely on some class
auto-registration mechanism.
Hi, thanks very much for the helpful replies. I'm happy that I was on
the right track!

Best wishes,
David.

Oct 30 '07 #5

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

Similar topics

2
1239
by: John Harrison | last post by:
I want to write a templated constructor with a non-type template argument, like this. class X { public: X() : val(0) {} template <int I> X(X const&, X const&) : val(I) {}
7
1812
by: bartek | last post by:
Hello, I've been pondering with this for quite some time now, and finally decided to ask here for suggestions. I'm kind of confused, actually... Maybe I'm thinking too much... Brain dump follows... I need a class to represent a variable, with an associated data type and/or value. Though, I don't want it to be a variant type, and not a
3
1912
by: Steve Brown | last post by:
Hello all, Is there a way to determine a variable's type at run-time? The reason I'm asking is that i have code that looks like this: template <class T> Object::Object(int TypeCode, T* data) { switch (TypeCode) case 1:
3
2721
by: case2005 | last post by:
Can anyone help with the following, I don't know if it's possible, but I'm certain there must be a standard way of dealing with this. I have the following: template<typename FooBar, typename Foo> class Bar { private: Foo foo;
0
1267
by: Chris Jefferson | last post by:
Now, C++ doesn't actually provide true variable-length templated classes, for example you can't do (as I found recently!) template<class T> class tuple { ... } template<class T, class U> class tuple { ... } There appear to be two main ways of "faking" this.
16
2970
by: frs | last post by:
See example below: Why does the output of 'a' work and the output of 'b' fails to compile? Is there a way to write class 'something' so that 'b' converts correctly by default? (include iostream, string, use namespace std) template <typename T> struct something { T x; operator T();
2
1492
by: Alex Drummond | last post by:
Hello, Is there any way of specializing a templated function on a type which is itself templated? Here's the simplest example of the problem I can think of. Say I have written an implementation of the identity function as follows, template <class T> T identity(T x) { return x; } and for some reason I want to specialize this function...
2
1796
by: Pete C | last post by:
Hello... I am writing a templated 'wrapper' class that takes as its template parameter a class to be inherited from. I need a specialisation of this wrapper class in certain cases, however I am having trouble with the specialisation when its parameter is itself a templated class. The following code compiles with g++ 4.0.3, however Comeau...
2
1915
by: Pierre Yves | last post by:
Hi there, Sorry for the double subject but I feel they are related. I'm not pretty sure there would be an answer but I reckon there must be a way to make it work. I would like to write the following bit of code: 8<----------------------------
0
7893
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. ...
0
8109
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...
1
7645
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...
0
6263
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...
1
5485
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...
0
5213
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...
0
3643
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...
1
2085
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
0
926
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...

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.