In general, there is a class LCgenerator , which uses the next() method to generate pseudo-random numbers. There is also a Sample class that should store values. I want to create a constructor of the Sample class that would call next() n times, thereby filling the selection.

Java programmers do this:

 interface Generator { next(); } class LCgenerator implemets Generator { // определяю next(); } class Sample { public Sample(Generator g, int n) { // вызывать n раз функцию next() из экземпляра g класса, // реализующего интерфейс Generator } } Sample s = new Sample( new LCGenerator(param), n); 

How is such a problem solved in c ++? Interfaces in the language there. Do abstract class? It seems to me somehow ugly, or something. Use function pointers? Well then, it is not clear how to transfer the method of a specific instance to such a function.

 template<class T> class Sample { //... Sample( T(*get)(), int n ); //... }; int main() { Sample<double> LC1( LCgenerator(1,7,3,32).next, 10000 ); //не компилит } 

Maybe somehow use a pointer to a method? In general, c ++ programmers, what solution (s) do you think is (are) beautiful (s)?

  • one
    And you do not know that the class of all methods which is virtual is the interface? - ArchDemon
  • @ArchDemon, was not aware, but in fact, yes. Those. c ++ programmers do abstract classes in such situations? - zer_ik
  • why not, especially plural inheritance is. - pavel

1 answer 1

Java style:

 class Generator{ public: virtual int next() = 0; virtual ~Generator(){} //Это важно! }; class LCgenerator : public Generator{ int next(){ return 42; } }; void foo(Generator *generator){ //Пользуемся генератором int i = generator->next(); } 

stl-style:

 class LCgenerator{ public: int operator()(){ return 42; } }; template<class Generator> void foo(Generator generator){ //Пользуемся генератором int i = generator(); } 

Not exactly stl-style, but very similar:

 class LCgenerator{ public: int next(){ return 42; } }; template<class Generator> void foo(Generator generator){ //Пользуемся генератором int i = generator.next(); } 

The first method is one-to-one as in your java example. Late binding is used with all resulting overhead during the execution phase. The second and third methods increase the compilation time, but at the execution stage, nothing extra happens.

It is also worth adding that the second method allows you to use not only class objects for which operator() is defined. As a generator, you can also pass pointers to functions and lambdas.