Is it possible to write a template function for which a particular type of classes have some functions or overloaded operators? For instance
template <typename T>
void dosomething(const T& x){
std::cout << x[0] << std::endl;
}
In this context I’m assuming that x is a class that behaves like an array, that is, I have overloaded the [] operator as well as the << so that it can work with std::cout.
The actual code that I have is slightly different but gcc is giving me
error: subscripted value is neither array nor pointer
This must be because it doesn’t know that I’m expecting T to be of some class that overloads the [] operator. Does anyone know if it is possible to overcome this? I’d like to let c++ know that the particular type T will have the [] overloaded.
You might need to provide a little more detail, as this short example works for me:
However, if you were to uncomment this line you would get a compiler error as std::vector doesn’t implement the << operator:
When you say this your thinking is on the right track:
However, the C++ compiler will actually search for [] operator at compile-time for any functions that request it. If there is no [] operator defined, you will get a compiler error. For example, this will cause a compiler error if inserted into the main() function:
You get this error message, similar to what you suggest in the question:
You can actually check if the [] exists at compile-time using the method outlined in this question:
How to check whether operator== exists?