Categories
Development

Pass function as template argument to a class

I want to pass functions as template arguments but somehow I can’t get it to work. I’ve written a lot of template classes in the past but only using “normal” types as arguments. I’ve already searched for that issue but nothing seems to fit here. So I’m stuck.

Here is what I want to achieve:
I have a couple of type specific library functions which I want to encapsulate. I know that there are other ways of doing it as well (e.g. inheritance) but since I also want to learn a little bit here, I want to get it done with the template approach.

What I want to achieve:

MyType<int> myIntObject(...);
...
int writeVal = 10;
myIntObject.Write(writeVal);
...
int readVal;
myIntObject.Read(&readVal);

Maybe also using typedefs:

typedef MyType<int> MyIntType;

What I did so far:

template<typename T>
struct SetFunction
{
  inline ret_code operator()(someArgs, T value) const {return E_Fail;}
}

template<typename T>
struct GetFunction
{
  inline ret_code operator()(someArgs, T& value) const {return E_Fail;}
}

//template specialization:
template<>
struct SetFunction<int>
{
  inline ret_code operator()(someArgs, T value) const
  {
    //some other code
    return libraryFunctionWriteInt(someArgs, value);
  }
}

template<>
struct GetFunction<int>
{
  inline ret_code operator()(someArgs, T& value) const
  {
    //some other code
    return libraryFunctionReadInt(someArgs, &value);
  }
}
//do the specialization for all other types as well

template<class T, typename T_get_function = GetFunction<T>(), typename T_set_function = SetFunction<T>()>
MyType
{
public:
  MyType(someArgs)
  {
    if(T_get_function(someArgs, &_value) == E_Fail)
    {
      throw someting;
    }
  }

  bool SetValue(T value)
  {
    _value = value;
    //maybe some other code
    return T_set_function(someArgs, _value) == E_Success;
  }

  bool GetValue(T &value)
  {
    //maybe some other code
    return T_get_function(someArgs, &_value) == E_Success;
  }

private:
  T _value;
}

//and then eventually using it (maybe using some typedefs as well)
MyType<int> myIntObject(someArgs);
...
int writeVal = 10;
myIntObject.SetValue(writeValue);
...
int readVal;
myIntObject.GetValue(&readValue);

Now I get compile errors: expression list treated as compound expression in functional cast on those two lines where I call the T_set_function / T_get_function. I also tried passing the library functions directly as template arguments and don’t set any default functions but I couldn’t get it to work that way as well.

Almost all of the books, articles and examples I read so far are only dealing with passing “normal” types as template arguments but since stl makes use of passing functions as well I really want to know how to do this.

Any help is welcome. 😉

Leave a Reply

Your email address will not be published. Required fields are marked *