How to overload the + operator for the inner class of a class template? I searched the clock and cannot find the answer. This is a minimal example that does not work:
#include <iostream>
using namespace std;
template <class T>
struct A
{
struct B
{
T m_t;
B(T t) : m_t(t) {}
};
};
template <class T>
typename A<T>::B operator+(typename A<T>::B lhs, int n)
{
lhs.m_t += n;
return lhs;
}
int main(int argc, char **argv)
{
A<float> a;
A<float>::B b(17.2);
auto c = b + 5;
cout << c.m_t << endl;
return 0;
}
If I compile this, I get error: no match for โoperator+โ (operand types are โA<float>::Bโ and โintโ)
I found somewhere that operator+(A<T>::B, int)should be declared, so if I add the following:
struct B;
friend B operator+(typename A<T>::B lhs, int n);
after struct A {, I get a linker error.
If I am not trying to call b + 5, the program compiles correctly.
How are they (STL program) programs vector<T>::iterator operator+with int? I can't find it anywhere (and it's hard to read stl_vector.h)!
Thank.
source
share