2

For example

template<class D, Function>
struct A
{
    void foo()
    {
        D d;
        int i = Function(d);
        // Here function can be a free function: int fun(D& d)
        // or member function: int D::fun()
        // or function object:
    }
};

How to set the template parameter to allow flexibility in choosing different kinds of functions? Code can be changed just allow the flexibility is fine. Thanks

user1899020
  • 13,167
  • 21
  • 79
  • 154
  • Is the question is about a [function passed as template argument](http://stackoverflow.com/questions/1174169/function-passed-as-template-argument)? – DrYap Aug 06 '13 at 16:42

1 Answers1

1

It's probably better to pass the function around into the class. If you don't pass some object around, you have to for example defaut construct such an object to call with:

template<class D, typename Function>
struct A
{
    explicit A(Function f) : func_(f) { }

    void foo()
    {
        D d;
        int i = func_(d);
        // Here function can be a free function: int fun(D& d)
        // or member function: int D::fun()
        // or function object:
    }

    Function func_;
};

Since callable types are almost always stateless or have tiny internal state there shouldn't be any implications for copying these.

Mark B
  • 95,107
  • 10
  • 109
  • 188
  • @user1899020 Very unlikely to matter. Function will be copied into the class, but functors are usually small. – Neil Kirk Aug 06 '13 at 16:50