How to create a vector of objects that share a concept?
4
I want to create a vector (or array) of objects of different types but all sharing the same concept.
similar to Vec<Box<dyn trait>>
of Rust.
struct Dog {
void talk() {
std::cout << "guau guau" << std::endl;
}
};
struct Cat {
void talk() {
std::cout << "miau miau" << std::endl;
}
};
template <typename T>
concept Talk = requires(T a) {
{ a.talk() } -> std::convertible_to<void>;
};
int main() {
auto x = Dog{};
auto y = Cat{};
??? pets = {x, y};
for(auto& pet: pets) {
pet.talk();
}
return 0;
}
c++ c++20 c++-concepts
-
Nope, C++ does not work this way. – Sam Varshavchik Apr 20 at 2:02
-
It is usually a bad idea to bring concepts from one language to another. – Slava Apr 20 at 2:06
-
Most likely you are heading in the wrong direction. You are probably looking for polymorphism. – zdf Apr 20 at 6:04
Add a comment
|