简体   繁体   中英

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?

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.

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 and error. Templates functions are basically contracts and as long as the type you are using conforms to the contract then it will work.

In this case I would also suggest you experiment with it, sites like LiveWorkSpace 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. You can find more such tools in this previous thread .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM