c++c++20c++-concepts

Create a vector of objects that satisfy a concept


I am trying to create a vector of different types of objects that all satisfy a given concept. My current attempt is something like this:

template<typename T>
concept Foo = requires(T t) {
// constraints...
};

std::vector<std::unique_ptr<Foo>> getFooVector();

I get that Foo is not a complete type, and I think I would have to use type erasure to make this work, but I am not quite sure how I would go about that. How could I make something like this work?


Solution

  • I am trying to create a vector of different types of objects

    This, strictly speaking is impossible, in the sense that all the objects that a std::vector<T> can hold, must all be of type T.

    Whether that T is a pointer (smart or not) and so can, in turn, point to entities of different type, that's another story.

    So I guess what you want can be obtained in two similar but not so similar ways:


    The why std::function manages to be able to store different lambdas (which by definition have different types) and any other callable is that it uses type erasure, a technique that deserves its own post.


    I think concepts are the wrong tool for your usecase.