Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I access a struct/class member from a template?

What I want to do is create a function that accepts any class or struct (via templates), but also have the function assume that there's always a specific member in the passed-in class or struct.

In probably-not-correct-code, it would look something like this:

template <class inputType>
int doSomething(inputType voxel)
{
    return voxel.density;
}

I want it to assume that density member will always be there and that it will always be an int (or whatever). Can I do that? And if so, what happens if density doesn't exist? Will it simply throw a compiler error?

like image 800
Clonkex Avatar asked Apr 17 '13 00:04

Clonkex


1 Answers

It's perfectly legal, templates in C++ are not comparable to a different approach (think Java) that type checks the generic method or classes by keeping the type variable.

A C++ template is compiled with every possible type you are using it, so every single instantiation for every specific type is compiled and type checked. If you try to access a field which is not contained in the type you are using doSomething with, then you will get a compiler error.

like image 53
Jack Avatar answered Sep 28 '22 12:09

Jack