static const reference to std::cout

Hey buddies,

is something as this possible?

Caution! This is invalid code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <string>

template <typename T>
struct Value {
    // this is not valid (since ostream is not an integral type [correct?]
    // shall i define a function, returning cout? 
    static const std::ostream &cout = std::cout;
}

template < >
struct Value <std::wstring> {
    // of course, this would apply here the same way
    static const std::wostream &cout = std::wcout;
}

// takes a string and print it in reverse order
template <typename TString>
void printReverse(TString str)
{
    // length is not defined here but i am sure, you know what it does
    for (int i = length(str) - 1; i >= 0; --i) {
        // here is the clue
        Value<TString>::cout << str[i];
    }
}


The thing is, i could accomplish this by defining a template function returning the appropriate ostream i need. But furthermore, i was thinking if it is possible not using functions but with such a class. But i slowly think this is not possible. So something like

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// this is possible, but is there an alternative?
// imagine Value<TString>::ostream retuns std::ostream or std::wostream
template <typename TString>
typename Value<TString>::ostream
cout() {
    return std::cout;
}

template < >
typename Value<wstring>::ostream
cout <wstring> () {
    return std::wcout;
}

template <typename TString>
void printReverse(TString str)
{
    // length is not defined here but i am sure, you know what it does
    for (int i = length(str) - 1; i >= 0; --i) {
        // here is the clue
        cout<TString>() << str[i];
    }
}


I don't like, that i am using a function. I would like to use objects more. (just for fun).
May i can declare a template class which can convert into an ostream depending on its type? Gosh.. there many ways, I think.

How would you do this?

Thanks, Maikel
You need to define a static member outside the class declaration:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
template <typename T>
struct Value {
    static std::ostream &cout;
};

template <typename T>
    std::ostream &Value<T>::cout = std::cout;

template < >
struct Value <std::wstring> {
    static std::wostream &cout;
};

std::wostream &Value<std::wstring>::cout = std::wcout;


( Notice that you can't use a const stream )
Last edited on
Topic archived. No new replies allowed.