1

In Java, when using genericism, you can specify what types are allowed to be used by doing something like this:

public class A<T inherits B>
{
   public A(T e);
}

If the semantics is wrong I'm sorry, I haven't written Java in quite a few years.

Is there a way to do so with templates in C++, and if so how? From what I have seen in my research so far, people seem to be doing it through the use of extra arguments, but that seems like a worse solution than using like a static_assert.

Something like this I guess:

template<typename T : std::vector>
class A
{
    A(T t) {}
};

In the example above T inherits from std::vector and as such allows for all potential classes that extend the capabilities of the STL vector class

Ohunter
  • 343
  • 1
  • 2
  • 13
  • `static_assert` was added in C++11. The solutions you saw might have been intended for C++03. – cdhowie Jun 05 '20 at 16:14
  • 3
    requiring inheritance from a base is rather untypical. Usually you only care about what operations the type supports, if it quacks like a duck then it is a duck, while you rather require it to have a label on its forhead saying "I am a duck" otherwise it isn't a duck, no matter how duck-like it is – 463035818_is_not_an_ai Jun 05 '20 at 16:16
  • Why just `std::vector`? What if someone wants to use `std::list`? Is there any reason they shouldn't be able to use `std::list` if it supports all of the operations that `A` is going to use? What if someone writes their own compatible container? Why can't they use that? – cdhowie Jun 05 '20 at 16:17
  • 2
    don't try to translate directly what you know from java generics to c++ templates, they are completely different worlds – 463035818_is_not_an_ai Jun 05 '20 at 16:17
  • btw also (publicly) inheriting from `std::vector` is rarely a good idea (or never?), standard containers are not meant to be inherited from, though one can write a container that has similar interface and can be used with all algorithms that also work for a `std::vector` – 463035818_is_not_an_ai Jun 05 '20 at 16:20

0 Answers0