wcout und cout überladbar?



  • Hola!
    Ich glaube, der Code zeigt, was ich vorhabe:

    template<typename T> 
    void open ( const T& t )
    {
    	ifstream in;
    	in.open(t.c_str());
    	if ( in == NULL )
    	{
    		if ( typeof(t) == string ) //error C2275: 'std::string': Ungültige Verwendung dieses Typs als Ausdruck
    			cout << "Kann " << t.c_str() << " nicht oeffnen!" << endl;
    		if ( typeof(t) == wstring )
    			wout << "Kann " << t.c_str() << " nicht oeffnen!" << endl;
    	}
    }
    

    Aufruf:

    string str ("test.txt");
    	wstring wstr(L"test.txt");
    	open(str);
    	open(wstr);
    

    Bloß mein Compiler, der mag das nicht:

    error C2275: 'std::string': Ungültige Verwendung dieses Typs als Ausdruck

    Was tun?



  • bool isString(string const&)
    {
       return true;
    }
    bool isString(wsrting const&)
    {
       return false;
    }
    ...
    if(isString(t))
    


  • Funzt super, danke!



  • Ginge nicht auch:

    if(typeof(t) == typeof(std::string)) {
       // ...
    }
    


  • DStefan schrieb:

    Ginge nicht auch:

    if(typeof(t) == typeof(std::string)) {
       // ...
    }
    

    nein. es gibt keinen == auf typen.
    vielleicht meinst du type_id mit RTTI. das ginge.



  • volkard schrieb:

    DStefan schrieb:

    Ginge nicht auch:

    if(typeof(t) == typeof(std::string)) {
       // ...
    }
    

    nein. es gibt keinen == auf typen.
    vielleicht meinst du type_id mit RTTI. das ginge.

    Nee, ich meinte typeof(), weil ich das nämlich nicht kenne. Und Google hat mir auf die Schnelle auch nicht weiter geholfen. Was ist denn die Rückgabe von typeof()?

    Stefan.



  • DStefan schrieb:

    Nee, ich meinte typeof(), weil ich das nämlich nicht kenne. Und Google hat mir auf die Schnelle auch nicht weiter geholfen. Was ist denn die Rückgabe von typeof()?

    Der Typ selber. Und den kannste auch nur nehmen, wo Typen gehen.
    kannst ja nicht if(int==int) schreiben.

    int a=5;//wenn ich diesen typ ändere, ändert der von b sich mit
    typeof(a) b=a+a;
    


  • Es gibt kein wirkliches typeof . Was du vielleicht meinst, ist decltype vom neuen Standard. Damit kann man an den Typen eines Ausdrucks rankommen. Mit == vergleichen geht trotzdem nicht.

    Um zwei Typen auf Gleichheit zu überprüfen, reichen Templates:

    template <typename T, typename U>
    struct is_same
    {
        static const bool value = false;
    };
    
    template <typename T>
    struct is_same<T, T>
    {
        static const bool value = true;
    };
    

    Anwendung:

    bool is_float_equal_to_int = is_same<float, int>::value;
    bool is_float_equal_to_float = is_same<float, float>::value;
    

Anmelden zum Antworten