Search code examples
c++c++20sfinaec++-concepts

How to SFINAE using concepts on member non-template function of a template struct?


Background

I'm writing an object pool. I would like to provide one constructor which just accepts the count of elements to default construct. There is a concept for that already, I would like to try to use C++20 feature for this.

Code

template <typename T, std::size_t capacity>
class object_pool {
/*
    storage for uninitialized objects
    used flags
    size
    etc...
*/

public:
    ??? object_pool(std::size_t count = capacity) {
        /* initialization */
    }

};

I can SFINAE the conventional way, which would look like:

template <typename = std::enable_if_t<std::is_default_constructible_v<T>>>
object_pool(std::size_t count = capacity) {
  /*...*/
}

Question

Can concepts be used to SFINAE on member function of template class/struct? If so, how to do it?


Solution

  • You can put a requires expression after the signature

    object_pool(std::size_t count = capacity) requires std::default_initializable<T> {
      /*...*/
    }
    

    Example