2

I want to write a generic interface. I need a list of different objects in a std::vector. Each of this objects has a other type but the same interface.

For example:

struct Base
{
  std::string name;

  virtual void doWork(???, ???);
  virtual void print(???,???);
};

struct ObjA : Base
{
  void doWork(???,???) override
  {
      std::cout << "Hello\n";
  };
  void print(???,???) override
  {
     std::cout << "Hey\n";
  };
}

struct ObjB : Base
{
 void doWork(???,???) override { std::cout << "Hello\n"; };
 void print(???,??? ) override { std::cout << "Hey\n";   };
}

But i don't know the type of ???,???. Since it is not possible to use virtual in combination with template's I'm searching for an elegant way.

Is it possible to solve this at compile time ?

Roby
  • 2,011
  • 4
  • 28
  • 55

3 Answers3

1

You could do this with variable arguments. In Base pass an integer for the number of arguments you are going to pass and then the variable arguments. Then use va_arg to get the actual parameters.

struct Base
{
    std::string name;

    virtual void doWork(int i, ...)
    {
    }
};

struct ObjB : Base
{
    void doWork(int i, ...) override 
    { 
        va_list ap;

        va_start(ap, i);

        int x = va_arg(ap, int);

        std::cout << x << std::endl;

        float f = va_arg(ap, float);

        std::cout << x << std::endl;

        va_end(ap);
    }
};

Base *base = new ObjB;

base->doWork(2, 10, 3.f);
Serve Laurijssen
  • 9,266
  • 5
  • 45
  • 98
0

This question could be marked as duplicated! But because you stated: "Since it is not possible to ...." and asked: "Is it possible to solve this at compile time?"

Please refer to this answer:

Can a C++ class member function template be virtual?

Community
  • 1
  • 1
Khoa
  • 2,632
  • 18
  • 13
0

Your unknown parameter types (???) smell like they also need to share a common interface to provide any useful information to your methods.

That would solve the problem in an elegant way, but obviously not at compile time.