Traits



  • Hallo Leute,
    ich habe eine Frage zum Thema Traits. Ich verstehe einfach nicht wie das Funktionieren soll. Ich habe es versucht zwischen Pointer und keinem Pointer Type zu unterscheiden - klappt.

    template< typename T >
    class TypeInfo
    {
    public:
    	TypeInfo( ) : isPtr( false )
    	{
    	}
    
    	typedef T a_type;
    
    	bool isPointer( )
    	{
    		return isPtr;
    	}
    private:
    	bool isPtr;
    };
    
    template< typename T >
    class TypeInfo< T* >
    {
    public:
    	TypeInfo( ) : isPtr( true )
    	{
    	}
    
    	bool isPointer( )
    	{
    		return isPtr;
    	}
    
    	typedef T* a_type;
    private:
    	bool isPtr;
    };
    

    Nun möchte ich mit Hilfe von einer Traits-Klasse eine zu dem Typ passende Funktion f aufrufen:

    template < typename T >
    void f( TypeInfo< T > )
    {
    }
    

    Ab hier weiß ich nicht weiter... Ich weiß man könnte einfach die Funktion spezialisieren, das wollte ich jedoch über die TypeInfo machen. Ist mein Ansatz richtig? Wenn nicht, was machen ich falsch? Ich hoffe es ist so halbwegs verständlich was ich meine. Ich würde mich über eine Erklärung freuen.

    MfG yihaaa



  • Dein TypeInfo ist falsch.

    template< typename T >
    class TypeInfo
    {
    public:
        enum { isPointer = 0 };
    };
    
    template<typename T>
    class TypeInfo<T*> {
    public:
        enum { isPointer = 1 };
    };
    

    dann kannst du checken ob ein Typ ein Zeiger ist:

    template<typename T>
    void print_yes_if_t_is_ptr() {
       helper<TypeInfo<T>::isPointer>::print();
    }
    
    template<bool B>
    class helper;
    
    template<>
    class helper<true> {
    public:
       static void print() { cout<<"yes\n"; }
    };
    
    template<>
    class helper<false> {
    public:
       static void print() { cout<<"no\n"; }
    };
    


  • Okay danke. Muss man also immer das Workaround gehen mit enum? Könnte man das auch mit const int machen?

    MfG



  • yihaaa schrieb:

    Okay danke. Muss man also immer das Workaround gehen mit enum? Könnte man das auch mit const int machen?

    enum oder static const int nimmt sich nicht viel.
    mit enum ists halt netter zu schreiben.


Anmelden zum Antworten