Allocator traits member types



  • namespace std {
        template <class Alloc> struct allocator_traits;
    }
    

    Im aktuellen C++ Entwurf in Sektion 20.9.4.1 (Allocator traits member types) steht folgendes über den typedef 'pointer':

    Type: Alloc::pointer if such a type exists; otherwise, value_type*.

    Meine Frage ist jetzt jedoch: Wie kann ich denn überprüfen ob es einen Typ "Alloc::pointer" gibt oder nicht?



  • Mit SFINAE - wikipedia zeigt wie:

    template <typename T>
    struct has_typedef_type
    {
        // yes and no are guaranteed to have different sizes,
        // specifically sizeof(yes) == 1 and sizeof(no) == 2
        typedef char yes[1];
        typedef char no[2];
    
        template <typename C>
        static yes& test(typename C::type*);
    
        template <typename>
        static no& test(...);
    
        // if the sizeof the result of calling test<T>(0) is equal to the sizeof(yes),
        // the first overload worked and T has a nested type named type.
        static const bool value = sizeof(test<T>(0)) == sizeof(yes);
    };
    


  • So z.B.:

    template<typename T>
    T& make();
    
    typedef char yes;
    typedef char no[2];
    
    template<typename T>
    yes& test(const T&, typename T::pointer* x = 0);
    no& test(...);
    
    template<typename T>
    struct has_pointer_type
    {
        static const bool value = sizeof(test(make<T>())) == sizeof(yes);
    };
    
    struct foo { typedef int* pointer; };
    struct bar {};
    
    int main()
    {
        std::cout << has_pointer_type<foo>::value << '\n'
                  << has_pointer_type<bar>::value << '\n';
    }
    

    Ausgabe:

    true
    false



  • Ich danke für eure Antworten. Fragt sich jetzt nur noch wo der Vorteil davon ist? Wenn ich einen std::allocator für einen Typ "Alloc" haben möchte, dann sollte mir allocate doch auch "Alloc*" liefern?!



  • FrEEzE2046 schrieb:

    Ich danke für eure Antworten. Fragt sich jetzt nur noch wo der Vorteil davon ist? Wenn ich einen std::allocator für einen Typ "Alloc" haben möchte, dann sollte mir allocate doch auch "Alloc*" liefern?!

    Ich weiss nicht ob es mit dem neuen Standard möglich ist - aber in der theorie könntest du proxys liefern um eben nicht rohen Speicher hergeben zu müssen. zB weil du zugriffe überprüfen willst, erst verspätet allokieren willst oder auch garbage collection einbauen willst, etc.

    Ob das ganze erlaubt ist, weiß ich nicht. Beim aktuellen C++ Standard ist es das leider nicht.



  • Shade Of Mine schrieb:

    Ob das ganze erlaubt ist, weiß ich nicht. Beim aktuellen C++ Standard ist es das leider nicht.

    Es ist derzeit noch etwas schwerer zu überschauen. std::allocator verwendet weiterhin die bekannten typedefs.


Anmelden zum Antworten