Reputation: 9035
The C++ language allows me to write a template function that will call a method on the object that gets passed to the function.
The concern here is when I do this, my IDE (NetBeans 8.2) will complain that it can't resolve the method. This makes sense because the type that will be used for "T" is not known until I try to compile the code, but the fact that it gives me a warning makes me a little concerned about whether or not doing this is bad programming practice.
Consider the following code:
struct S1 {
void method() const {
cout << "Method called from S1!" << endl;
}
};
struct S2 {
void method() const {
cout << "Method called from S2!" << endl;
}
};
template <typename T>
void call_method(const T& object) {
// IDE reports a warning "can't resolve the template based identifier method."
object.method();
}
Usage example:
S1 obj1;
S2 obj2;
call_method(obj1);
call_method(obj2);
This code will compile and work just fine, but the IDE will always complain. Is this okay to do? Or is there a better design that I should know about to get the same desired results.
The desired result is to write a function that can use S1 or S2 objects without caring which one it is as long as they provide an interface that includes "method()".
Assume I do not have access to the source code of S1 and S2 so I can't make changes to them. (For example I cannot make them inherit from a common base class and use dynamic polymorphism instead of a template function to achieve the same effect).
Upvotes: 0
Views: 1032
Reputation: 12938
This is perfectly OK and is commonly used in a lot of cases. Dealing with a generic container from the standard library or different types of iterators for example.
If the type passed in does not have an appropriate method you will get a compilation error.
If you want you can use SFINAE to make sure the type passed in is among the types you expect. Can be good or useful sometimes, but often not needed.
Update: static_assert
is another useful way of putting constraints on a template as pointed out by @Evgeny
Upvotes: 5