Home > front end >  How to create a Template function that creates an instance of the class specified as a template para
How to create a Template function that creates an instance of the class specified as a template para

Time:08-10

I am trying to enumerate my I2C bus. I have a data structure that contains the I2C address range, the device name and a pointer to the function that needs to be called to "Create" that device. The Create Device functions are all very similar and I was wondering if I can create a template function, instead of creating n functions that only differ in the name of the device that they are creating A typical create function looks like this (the name AMS3935Creator is stashed in the data structure above and when that device is encountered, this function is called).

I2cDeviceBase * AMS3935Creator ( I2cInterfaceBase & i2cBus, uint8_t i2cAddress, DeviceFactory * dfObject )
{
  return new AMS3935 ( i2cBus, i2cAddress ) ;
}

I tried to work this out like this, but the template function does not compile (See error comment below), is there a way to accomplish this ?

#include <stdio.h>

class BaseClass {
  protected:
    BaseClass () {} ;
    BaseClass ( int param1, int param2 ) { printf ( "in BaseClass Constructor\n" ) ; } ;

} ;

class ClassA : public BaseClass {
  public: 
   // ClassA () {} ;
    ClassA ( int param1, int param2 ) { printf ( "in ClassA Constructor\n" ) ; } ;
  } ;

class ClassB : public BaseClass {
  public: 
    ClassB () {} ;
    ClassB ( int param1, int param2 ) { printf ( "in ClassB Constructor\n" ) ; } ;
} ;

template <typename ClassName> 
  BaseClass * TemplateTest( int param1, int param2, ClassName className ) {
    BaseClass * bcPointer = new className ( param1, param2 ) ; // error: expected type-specifier before ‘className’
    return bcPointer ;
}

CodePudding user response:

To your title question

template<typename T> 
T create(){  return T{}; }

As to you actual question. It is most of the time very tricky, sometimes bordering on impossible to make templates and inheritance play nice with each other. Also ClassName className in the argument list makes className a value. You cant do

new value; // needs to be a type. 

If this was intended to be ClassName, see my first suggestion.

My suggestion is: Scrap this design and redo it from scratch.

  • Related