Clonkex
Clonkex

Reputation: 3637

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?

Upvotes: 6

Views: 4177

Answers (2)

Shafik Yaghmour
Shafik Yaghmour

Reputation: 158469

You can definitely do this, templates are going to be instantiated at compile time and if the type does not have that member it will not compile and you will receive an error. Templates functions are basically contracts and as long as the type you are using conforms to the contract, it will work.

In this case I would also suggest you experiment with it, sites like C++ Shell and onlinegdb.com make experimenting with C/C++ pretty easy and painless anywhere you are and they support the latest versions. You will learn a lot more by trying out things like this.

Upvotes: 1

Jack
Jack

Reputation: 133577

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.

Upvotes: 5

Related Questions