Overloading << for template problem

Hi, I have a problem with my code. I have template and Im using it for a wchar_t T parameter.


1
2
3
4
5
6
7
8
9
10
11
12
13
template <class T>
class ValueTemplate
{
public:

    T value;

    friend std::wofstream& operator<< (std::wofstream& out, Temp<T>& v)
    {
        out << v.value;
        return out;
    }
};


Problem:

I have a error:

C2679: binary '<<' : no operator found which takes a right-hand operand of type 'T' (or there is no acceptable conversion.



I was trying change it to const, non-reference, but everytime I have this error message.
When I change it for a ofstream, everything works great with no errors.

There is something I make in the wrong way?
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <fstream>

template <class T>
class ValueTemplate
{
    T value;
public:
    ValueTemplate(T v) : value(v) {}
    friend std::wostream& operator<< (std::wostream& out, const ValueTemplate<T>& v)
    {
        return out << v.value;
    }
};

int main() {
    ValueTemplate<int> vt(42);
    std::wcout << vt << '\n';
}

But what if I want something like that:

1
2
3
int main() {
    ValueTemplate<wchar_t>...
}

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

template <class T>
class ValueTemplate
{
    T value;
public:
    ValueTemplate(T v) : value(v) {}

    friend std::wostream& operator<<(std::wostream& out, const ValueTemplate<T>& v)
    {
        return out << v.value;
    }
};

int main() {
    ValueTemplate vt(L'X');       // wchar_t
    std::wcout << vt << '\n';
    ValueTemplate vt2(L"hello");  // const wchar_t*
    std::wcout << vt2 << '\n';
}

Topic archived. No new replies allowed.