How to overload a free function for a member type template

I have a template class that defines some types of members. This is similar to how it std::mapdefines it value_typebased on its own template arguments, but in my case the type is more complex, so it is defined as a nested class.

Now for debugging I would like to define operator<<for this type. But the compiler tells me that it cannot output the template parameters of the external template.

My real code is not contrived as the following example, but this contrived example demonstrates the approach I tried and how it fails:

#include <iostream>

template <typename Value> class Outer;

template <typename Value>
std::ostream &operator<<(std::ostream &, const typename Outer<Value>::Inner &);

template <typename Value>
class Outer {
  public:
    struct Inner {
    Value x;
    };

    void PrintSomething(Value v) {
    // the real program does something useful with the inner class, of course
    Inner inner = { v };
    std::cout << "Inner = " << inner << std::endl; // <---- THIS SAYS IT CAN'T FIND operator<<
    };
};

template <typename Value>
std::ostream &operator<<(std::ostream &s, const typename Outer<Value>::Inner &v) {
    return s << v.x;
}

int main() {
    Outer<int> o;
    o.PrintSomething(42);
    return 0;
}

, . ( 3 ) , operator<<, Outer<int>::Inner. , , C2783: could not deduce template argument for 'identifier', gcc clang , , Outer<int>::Inner).

, operator<<, Outer<Value>::Inner Value, ( ) ?

. , , - ++ 11, , ++ 03.

+5
1

. Value? , ( .. , ).

: Inner Outer operator<< . - , .

template<class T>
struct Outer{
  struct Inner{
    T value;
    friend std::ostream& operator<<(std::ostream& os, Inner const& v){
      return os << v.value:
    }
  };
  // ...
};
+6

All Articles