Operator + C ++ + overload in inner class

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.

+4
source share
2 answers

, , , , :

template <class T>
typename A<T>::B operator+(typename A<T>::B lhs, int n)

typename A<T>::B lhs - . , T , , operator+. :

template <class T> void foo(typename T::type );

struct A { using type = int; };
struct B { using type = int; };

foo(0); // what would T be? 
        // how many other possible T are there that fit?

, , . :

auto c = ::operator+<float>(b, 5);

, , !


operator+ struct B:

struct B
{
    T m_t;
    B(T t) : m_t(t) {}

    // member
    B operator+(int n) {
        return B(m_t + n);
    }

    // or non-member, non-template friend
    friend B operator+(B lhs, int n) {
        lhs.m_t += n;
        return lhs;
    }
};
+2

, - :

#include <iostream>
#include <type_traits>
using namespace std;

template <class T>
struct A
{
    struct B
    {
        typedef A<T> OuterType;
        T m_t;
        B(T t) : m_t(t) {}
    };


};

template <class T>
typename T::OuterType::B operator+(T 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;
}

: , T (b + 5) , OuterType, B . , , T, typename enable_if<is_same<T, typename T::OuterType::B>::value, T>::type : typename T::OuterType::B

0

All Articles