C++ Templates: Pass Type, not instance?

Templates may not be the answer here but I tried some inheritance and that didn't work so here is where I am at.

The Problem:

I have an abstract base class that houses all my "work" functions. I'll then have a bunch of other classes that extend that base class and essentially just fill in the details of the data to pass down into the "work" functions as well as overriding a couple of the base classes functions.

One of the main pieces of data that will change in each derived class is a struct.

So my initial plan of attack was to have a BaseStruct defined and the abstract base class just did all of it's work on that base struct. If the derived classes used a different struct that extended that base struct then that's fine.

The problem I ran into with this is that I couldn't get the size of the struct since in the work function the type of the struct it was operating on is a BaseStruct rather than the derived type.

So now I'm looking at templates.

Essentially I want to have a Base function that does this:

template<typename StructType>
void AbstractMaterial::CreateVertexBuffer() {

    StructType* array = new StructType[numVertices];

    size_t si = sizeof(StructType) * numVertices;


Of course without actually passing anything into this function, it doesn't really work. I'd rather not create an instance of StructType to pass in just to get the type information but it doesn't seem like there is any other way?

Essentially I want derived classes to someone specify a StructType to use when this function is called.



This invocation should work:

For class (static) function:


For member function:


You can specify the type by writing it in between <> before the parentheses. For example:

// supposing asm is an AbstractMaterial*

Need Your Help

How to know what's a stub?

assembly rmi mips corba stub

Does stub always mean the same thing when you write programs?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.