How to let C++ know that an operator has been overloaded for a class
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 tha开发者_如何学Got the particular type T
will have the []
overloaded.
You might need to provide a little more detail, as this short example works for me:
#include <iostream>
#include <vector>
template <typename T>
void dosomething(const T& x){
std::cout << x << std::endl;
}
template <typename T>
void dosomething_else(const T& x){
std::cout << x[0] << std::endl;
}
int main() {
dosomething< int >(1) ;
std::vector< int > vec( 3, 1 );
//dosomething< std::vector< int > >(vec);
dosomething_else< std::vector< int > >(vec);
}
However, if you were to uncomment this line you would get a compiler error as std::vector doesn't implement the << operator:
//dosomething< std::vector< int > >(vec);
When you say this your thinking is on the right track:
I'd like to let c++ know that the particular type T will have the [] overloaded.
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:
dosomething_else< int >(1);
You get this error message, similar to what you suggest in the question:
test.cpp: In function 'void dosomething_else(const T&) [with T = int]':
test.cpp:19: instantiated from here
test.cpp:11: error: subscripted value is neither array nor pointer
You can actually check if the [] exists at compile-time using the method outlined in this question: How to check whether operator== exists?
Make sure the method that declares the operator overload is marked const
.
You can either:
1) define a simple class that has []
overloaded, inherit from it, and use that as the argument type instead of T.
2) cast the argument to some type that has your implementation of []
Instead of x[0]
use x.operator[](0)
.
It won't be enough to overload operator <<
for class T, you'll have to do it for the type that operator []
returns.
精彩评论