473,587 Members | 2,533 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

alternative for virtual template function?

I have an abstract base class which contains a function that I would
like to template, but virtual template functions are illegal. I put a
mini code example below, which doesn't do anything great, but reflects
the structure of my problem.

In a nutshell, the abstr. base class VectorCreator has a function
createVector whose return type is unfortunately fixed to
vector<double>. Only now I discovered that some implementations would
like to work with other types, such as vector<int>. I could just
template the VectorCreator class, but the problem is that pointers to
VectorCreator are passed around in the whole project, so templating it
would require too many changes. It's okay to change the createVector
function, but not the whole VectorCreator class (by introducing a
class-scope template). Here is the example code:

#include <iostream>
#include <vector>

// ABC
class VectorCreator {
public:
virtual ~VectorCreator( ) {}
virtual std::vector<dou ble>* createVector() = 0; // it's illegal to
template the function :(
};

// concrete implementation example
class VectorCreator1 : public VectorCreator {
typedef std::vector<dou bleT;
public:
VectorCreator1( ) {}
~VectorCreator1 () {}
T* createVector() {
T* type = new T();
type->push_back(10.2 );
return type;
}
};

// like foo here, there are many fct's and classes that are called or
// initialized with VectorCreator*, so VectorCreator cannot be
// templated (would require changing hundreds of source files)
void foo(VectorCreat or* sc){
std::vector<dou ble>* myvector = sc->createVector() ;
std::cout << (*myvector)[0] << std::endl;
delete myvector;
}

int main(double argc, char** argv){
VectorCreator* sc = new VectorCreator1( );
foo(sc);
delete sc;
return EXIT_SUCCESS;
}

I think I found an acceptable solution (see below), but I was
wondering if anyone has a better idea how to deal with this problem. I
heard that the Visitor pattern might help in situations where one
would like virtual templates, but I don't know how.
#include <iostream>
#include <vector>

// ABC
class VectorCreator {
public:
virtual ~VectorCreator( ) {}
virtual void createVector(st d::vector<doubl e>*&) = 0;
virtual void createVector(st d::vector<int>* &) = 0;
};

// concrete class example
class DoubleVectorCre ator : public VectorCreator {
public:
DoubleVectorCre ator() {}
~DoubleVectorCr eator() {}
void createVector(st d::vector<doubl e>*& x) {
x = new std::vector<dou ble>();
x->push_back(10.2 );
}
void createVector(st d::vector<int>* & x) {
std::cerr << "unimplemented" ;
}
};

class IntVectorCreato r : public VectorCreator {
public:
IntVectorCreato r() {}
~IntVectorCreat or() {}
void createVector(st d::vector<int>* & x) {
x = new std::vector<int >();
x->push_back(10 );
}
void createVector(st d::vector<doubl e>*& x) {
std::cerr << "unimplemented" ;
}
};

void foo(VectorCreat or* sc){
// specialized behaviors
if(dynamic_cast <DoubleVectorCr eator*>(sc)){
std::vector<dou ble>* myvector;
sc->createVector(m yvector);
std::cout << (*myvector)[0] << std::endl;
delete myvector;
}
else if(dynamic_cast <IntVectorCreat or*>(sc)){
std::vector<int >* myvector;
sc->createVector(m yvector);
std::cout << (*myvector)[0] << std::endl;
delete myvector;
}
}

int main(double argc, char** argv){
VectorCreator* sc = new DoubleVectorCre ator();
foo(sc);
delete sc;

VectorCreator* sc2 = new IntVectorCreato r();
foo(sc2);
delete sc2;

return EXIT_SUCCESS;
}

Thanks!
Markus

Jul 23 '08 #1
3 2338
I have an abstract base class which contains a function that I would
like to template, but virtual template functions are illegal. I put a
mini code example below, which doesn't do anything great, but reflects
the structure of my problem.

In a nutshell, the abstr. base class VectorCreator has a function
createVector whose return type is unfortunately fixed to
vector<double>. Only now I discovered that some implementations would
like to work with other types, such as vector<int>. I could just
template the VectorCreator class, but the problem is that pointers to
VectorCreator are passed around in the whole project, so templating it
would require too many changes. It's okay to change the createVector
function, but not the whole VectorCreator class (by introducing a
class-scope template).
I think you'd better template the class. The problem with old code can
be
circumventÅd by introducing a new class template and typdef-ing it:

template<typena me T>
class VectorCreatorTe mpl {
public:
virtual ~VectorCreator( ) {}
virtual std::vector<T>* createVector() = 0;
};

typedef VectorCreatorTe mpl<doubleVecto rCreator;
BTW: For factory functions it is generally preferred to return an
auto_ptr
instead of a raw pointer.
Jul 23 '08 #2
On 23 jul, 02:48, Markus Dehmann <markus.dehm... @gmail.comwrote :
I have an abstract base class which contains a function that I would
like to template, but virtual template functions are illegal. I put a
mini code example below, which doesn't do anything great, but reflects
the structure of my problem.

In a nutshell, the abstr. base class VectorCreator has a function
createVector whose return type is unfortunately fixed to
vector<double>. Only now I discovered that some implementations would
like to work with other types, such as vector<int>. I could just
template the VectorCreator class, but the problem is that pointers to
VectorCreator are passed around in the whole project, so templating it
would require too many changes. It's okay to change the createVector
function, but not the whole VectorCreator class (by introducing a
class-scope template). Here is the example code:

#include <iostream>
#include <vector>

// ABC
class VectorCreator {
public:
* virtual ~VectorCreator( ) {}
* virtual std::vector<dou ble>* createVector() = 0; // it's illegal to
template the function :(

};

// concrete implementation example
class VectorCreator1 : public VectorCreator {
* typedef std::vector<dou bleT;
public:
* VectorCreator1( ) {}
* ~VectorCreator1 () {}
* T* createVector() {
* * T* type = new T();
* * type->push_back(10.2 );
* * return type;
* }

};

// like foo here, there are many fct's and classes that are called or
// initialized with VectorCreator*, so VectorCreator cannot be
// templated (would require changing hundreds of source files)
void foo(VectorCreat or* sc){
* std::vector<dou ble>* myvector = sc->createVector() ;
* std::cout << (*myvector)[0] << std::endl;
* delete myvector;

}

int main(double argc, char** argv){
* VectorCreator* sc = new VectorCreator1( );
* foo(sc);
* delete sc;
* return EXIT_SUCCESS;

}

I think I found an acceptable solution (see below), but I was
wondering if anyone has a better idea how to deal with this problem. I
heard that the Visitor pattern might help in situations where one
would like virtual templates, but I don't know how.

#include <iostream>
#include <vector>

// ABC
class VectorCreator {
public:
* virtual ~VectorCreator( ) {}
* virtual void createVector(st d::vector<doubl e>*&) = 0;
* virtual void createVector(st d::vector<int>* &) = 0;

};

// concrete class example
class DoubleVectorCre ator : public VectorCreator {
public:
* DoubleVectorCre ator() {}
* ~DoubleVectorCr eator() {}
* void createVector(st d::vector<doubl e>*& x) {
* * x = new std::vector<dou ble>();
* * x->push_back(10.2 );
* }
* void createVector(st d::vector<int>* & x) {
* * std::cerr << "unimplemented" ;
* }

};

class IntVectorCreato r : public VectorCreator {
public:
* IntVectorCreato r() {}
* ~IntVectorCreat or() {}
* void createVector(st d::vector<int>* & x) {
* * x = new std::vector<int >();
* * x->push_back(10 );
* }
* void createVector(st d::vector<doubl e>*& x) {
* * std::cerr << "unimplemented" ;
* }

};

void foo(VectorCreat or* sc){
* // specialized behaviors
* if(dynamic_cast <DoubleVectorCr eator*>(sc)){
* * std::vector<dou ble>* myvector;
* * sc->createVector(m yvector);
* * std::cout << (*myvector)[0] << std::endl;
* * delete myvector;
* }
* else if(dynamic_cast <IntVectorCreat or*>(sc)){
* * std::vector<int >* myvector;
* * sc->createVector(m yvector);
* * std::cout << (*myvector)[0] << std::endl;
* * delete myvector;
* }

}

int main(double argc, char** argv){
* VectorCreator* sc = new DoubleVectorCre ator();
* foo(sc);
* delete sc;

* VectorCreator* sc2 = new IntVectorCreato r();
* foo(sc2);
* delete sc2;

* return EXIT_SUCCESS;

}

I'd template the class or the function and refactor the code. If
you're going to start using dynamic_cast across all of your code, you
don't even need the createVector() function as a virtual in the base
class. Just dynamic cast to the appropriate pointer and call a
function such as createIntVector () or createDoubleVec tor() which you
can create in the derived classes.

--
Leandro T. C. Melo
Jul 24 '08 #3
Markus Dehmann wrote:
I have an abstract base class which contains a function that I would
like to template, but virtual template functions are illegal. I put a
mini code example below, which doesn't do anything great, but reflects
the structure of my problem.

In a nutshell, the abstr. base class VectorCreator has a function
createVector whose return type is unfortunately fixed to
vector<double>. Only now I discovered that some implementations would
like to work with other types, such as vector<int>. I could just
template the VectorCreator class, but the problem is that pointers to
VectorCreator are passed around in the whole project, so templating it
would require too many changes. It's okay to change the createVector
function, but not the whole VectorCreator class (by introducing a
class-scope template). Here is the example code:
<snip>
#include <iostream>
#include <vector>

// ABC
class VectorCreator {
public:
virtual ~VectorCreator( ) {}
virtual void createVector(st d::vector<doubl e>*&) = 0;
virtual void createVector(st d::vector<int>* &) = 0;
};

// concrete class example
class DoubleVectorCre ator : public VectorCreator {
public:
DoubleVectorCre ator() {}
~DoubleVectorCr eator() {}
void createVector(st d::vector<doubl e>*& x) {
x = new std::vector<dou ble>();
x->push_back(10.2 );
}
void createVector(st d::vector<int>* & x) {
std::cerr << "unimplemented" ;
}
};

class IntVectorCreato r : public VectorCreator {
public:
IntVectorCreato r() {}
~IntVectorCreat or() {}
void createVector(st d::vector<int>* & x) {
x = new std::vector<int >();
x->push_back(10 );
}
void createVector(st d::vector<doubl e>*& x) {
std::cerr << "unimplemented" ;
}
};

void foo(VectorCreat or* sc){
// specialized behaviors
if(dynamic_cast <DoubleVectorCr eator*>(sc)){
std::vector<dou ble>* myvector;
sc->createVector(m yvector);
std::cout << (*myvector)[0] << std::endl;
delete myvector;
}
else if(dynamic_cast <IntVectorCreat or*>(sc)){
std::vector<int >* myvector;
sc->createVector(m yvector);
std::cout << (*myvector)[0] << std::endl;
delete myvector;
}
}

int main(double argc, char** argv){
VectorCreator* sc = new DoubleVectorCre ator();
foo(sc);
delete sc;

VectorCreator* sc2 = new IntVectorCreato r();
foo(sc2);
delete sc2;

return EXIT_SUCCESS;
}
Notice that the foo() function is switching on type. This is a classic
anti-pattern, which is resolved by implementing foo() in the
VectorCreator class itself.

i.e.

void DoubleVectorCre ator::foo()
void IntVectorCreato r::foo()

(There are other ways of switching on type too, such as function
overloading and templates.)

The question is what you need to *do* with these vectors/factories, that
requires them to have the same base class? What's the common
functionality? If they are logically separate then the only moral thing
to do is to separate them in your code.

The 'std::cerr<<"un implemented"' line is another OO anti-pattern. It's
normal for factories to create objects with a common base class (e.g.
my_vector):

std::auto_ptr<m y_vectorIntVect orCreator::crea te()
std::auto_ptr<m y_vectorDoubleV ectorCreator::c reate()

If you don't like dynamic memory allocation and virtual functions, then
try templates.

Hope that helps a little,

Calum
Jul 25 '08 #4

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

Similar topics

9
10274
by: Sebastian Faust | last post by:
Hi, I have a design problem about which I am thinking now for a while and still couldnt find any help in deja. What I need is something like a virtual function template. I know that this is not possible, so I need "something like" a virtual function template. I read in some threads that there is a workaround using the visitor pattern. I...
8
2042
by: puzzlecracker | last post by:
Can the template method be virtual and what are the consequences? Can the template inline functions be virtual and what are the consequences?
6
3994
by: RainBow | last post by:
Greetings!! I introduced the so-called "thin-template" pattern for controlling the code bloat caused due to template usage. However, one of the functions in the template happens to be virtual as well. To support thin-template, I need to make virtual function as inline. Now, I know that compiler would generate an out-of-line copy when it
3
3930
by: Chris | last post by:
I am having a very strange problem involving virtual functions in template classes. First of all, here is an extremely simplified structure of the two classes I am having problems with. template<class Type> class base { public: base& operator/=(const base&); Type *image;
11
3419
by: Nindi73 | last post by:
A few days a ago I posted my code for a deep copy pointer which doesn't require the pointee object to have a virtual copy constructor. I need help with checking that it was exception safe and exception neutral/ I got a reply from Bux with his code for a smart pointer with far fewer lines of code and more cleaner design, not over engineered...
11
2735
by: mathieu | last post by:
Hi there, I don't think I'll be able to describe my issue correctly, so instead I'll just give a pseudo C++ code I am struggling with. Basically I am looking for a 'pure virtual template' function that I would be able to declare in the base class (*). Thanks for suggestions, -Mathieu
2
2402
by: cmonthenet | last post by:
Hello, I searched for an answer to my question and found similar posts, but none that quite addressed the issue I am trying to resolve. Essentially, it seems like I need something like a virtual static function (which I know is illegal), but, is there a way to provide something similar? The class that is the target of my inquiry is a...
13
7251
by: Mike -- Email Ignored | last post by:
Is a pure virtual function in allowed in a template base class? In any case, I have one working. Am I skating on thin ice? Thanks, Mike.
5
2951
by: want.to.be.professer | last post by:
For OO design, I like using virtual member function.But considering efficiency, template is better. Look at this program, class Animal { public: virtual void Walk() = 0; }; class Dog
0
7923
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...
0
8216
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
8221
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...
0
6629
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...
0
3845
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...
0
3882
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2364
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
1
1455
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1192
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.