-2

My main question is: can I put the generic type before a class definition?

Like, can I do something like this:

generic class Classname (ParameterType parameter)
{
     cout << "Hello world";
}
S.I.M.P.L.E
  • 695
  • 1
  • 5
  • 10
  • 1
    What is this "`generic` type"? Is `generic` supposed to be a keyword? (It's not a keyword in C++.) – JaMiT Dec 07 '19 at 23:38
  • related: https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – UKMonkey Dec 07 '19 at 23:40
  • 1
    Your question is unclear. What do you mean by a "generic" type? What do you expect to be able to do with such a type? Without such clarification - in your question - there is no way to judge if any answer given is useful or even relevant. – Peter Dec 08 '19 at 01:00
  • Your code snippet looks like a function, not a class. A class has no parameters and no function body. – Thomas Sablik Dec 08 '19 at 02:38

1 Answers1

3

Templates are the way to do generics in C++. You can write it like this:

template<class ItemType> class ClassName
{
public:
   ClassName(const ItemType& newdata) : data(newdata) {}
private:
   ItemType data;
};

Later on in main:

ClassName<int> data1(1);
ClassName<char> data2('A');
bhristov
  • 3,137
  • 2
  • 10
  • 26
  • While what you say here is correct, the original question is so unclear, it is not possible to even determine if this answer addresses the question. – Peter Dec 08 '19 at 00:58
  • I know. I am just giving him an example of what generics looks like in C++. – bhristov Dec 08 '19 at 01:34