0

The following TestClass works:

#include <iostream>
#include <boost/function.hpp>
#include <boost/bind.hpp>

void ext_fun(const float f, int i)
{
    std::cout << f << '\t' << i << std::endl;
}

template <typename T>
class TestClass
{
public:
    boost::function <void (const T)> test_fun;
};

int main()
{
    TestClass<float> tt;
    tt.test_fun = std::bind(ext_fun, std::placeholders::_1, 10);
    tt.test_fun(2.1);
    return(0);
}

However, I would prefer to define test_fun as a member function template, i.e., something like

class TestClass
{
public:
    template <typename T> boost::function <void (const T)> test_fun;
};

But if I do it, I get this compiler error: "error: data member ‘test_fun’ cannot be a member template"

Is it possible to define a member function template using a boost::function? If yes, how?

Thank you

--Matteo

Matteo M.
  • 65
  • 1
  • 3
  • Sorry, that doesn't make sense - that's not what "function template" means. You're asking the equivalent of "can I turn `struct Foo { int a; };` into `struct Foo { template T a; };`", which you cannot. – Kerrek SB Jan 11 '14 at 06:22
  • @Kerrek SB I was referring to something like the very first example [here](http://msdn.microsoft.com/en-us/library/swta9c6e%28VS.80%29.aspx), or the question [here](http://stackoverflow.com/questions/972152/how-to-create-a-template-function-within-a-class-c), but using the `boost::function` – Matteo M. Jan 11 '14 at 07:34

1 Answers1

1

Is it possible to define a member function template using a boost::function? If yes, how?

I think you have a little bit of confusion going on here. A function template is, first of all, a function. Your test_fun is not a function, it's a member object of the class TestClass. Member objects can't be templatized in C++.

Shoe
  • 74,840
  • 36
  • 166
  • 272
  • Ok, so the point is: class methods can be templatized (like [here](http://msdn.microsoft.com/en-us/library/swta9c6e%28VS.80%29.aspx)), but if I use `boost::function` I do not actually have a method but a member **object** instead. So it cannot be templatized. Is this correct? – Matteo M. Jan 11 '14 at 08:10
  • @MatteoM., the "class method" terminology doesn't exists in C++: you should get used to "member function" instead. But yeah, the concept is correct. A `boost::function` is a class type, which leads the declaration `boost::function test_fun;` to be an object, which cannot be templatized. – Shoe Jan 11 '14 at 08:15