vendredi 29 juin 2018

Using SFINAE to resolve allocator member conditionally

I am writing a constructor for a list data structure.

template <class T, class Allocator = std::allocator<T>>
class list {

...
}

The class takes an Allocator template parameter and defaults to std::allocator if none is provided. Since C++11 allocators may have state the default constructor also takes an allocator object.

//    *** CONSTRUCTORS ***
explicit list(const Allocator& alloc = Allocator()): alloc_(alloc), head_(nullptr), tail_(nullptr), size_(0) {
    if(std::is_same<Allocator, customAllocator<T>>::value) {
        std::cout << "****" << std::endl;
        std::cout << alloc.member_ << std::endl;
        std::cout << alloc_.member_ << std::endl;
        std::cout << "****" << std::endl;
    }
}

When a custom allocator that contains 'member_' is provided the following lines execute without failure.

However when a std::allocator is passed the compiler understandably complains that there is no member 'member_' in the allocator.

However is there a way so that the std::cout lines are printed when a custom allocator is provided and not printed when the std::allocator (or any allocator without 'member_') is provided?

Thank you

Aucun commentaire:

Enregistrer un commentaire