samedi 25 juillet 2020

overloading operator<< for type nested in templated class [duplicate]

I am having some trouble overloading operator<< for output for my custom class. The class is nested within a templated type. Here is what I have tried( I get no errors for overloading operator<< for the outer class):

#include <iostream>

template <typename T>
class Foo {

/* types */
public:
    class Bar {
    private:
        T m_y; 
    
    public:
        Bar(const T& y);

        template <typename U>
        friend auto operator<< (std::ostream& os, const typename Foo<U>::Bar& b) -> std::ostream&; 
    };

private:
    T m_x; 

public:
    Foo(const T& x);


    template <typename U>
    friend auto operator<< (std::ostream& os, const Foo<U>& f) -> std::ostream&;
};


/* Foo */
template <typename T>
Foo<T>::Foo(const T& x) 
    : m_x{ x } {} 

template <typename T>
auto operator<< (std::ostream& os, const Foo<T>& f) -> std::ostream& {
    return os << f.m_x;
}


/* Bar */
template <typename T>
Foo<T>::Bar::Bar(const T& y) 
    : m_y{ y } {}

template <typename T>
auto operator<< (std::ostream& os, const typename Foo<T>::Bar& b) -> std::ostream& {
    return os << b.m_y;
}


int main() {
    Foo<int>::Bar b{ 15 }; 

    std::cout << b << '\n'; 
    return 0; 
}

and here are the errors I get when compiling with MinGW( can't show all of it because SO won't let me):

things/array/main.cpp: In function 'int main()':
things/array/main.cpp:58:15: error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'Foo<int>::Bar')
     std::cout << b << '\n'; 
               ^
C:/Program Files (x86)/CodeBlocks/MinGW/lib/gcc/mingw32/5.1.0/include/c++/bits/basic_string.h:5167:5: note:   template argument deduction/substitution failed:
things/array/main.cpp:58:18: note:   'Foo<int>::Bar' is not derived from 'const std::__cxx11::basic_string<_CharT, _Traits, _Alloc>'
     std::cout << b << '\n'; 
                  ^
make: *** [Makefile:16: array] Error 1

Aucun commentaire:

Enregistrer un commentaire