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

2
  • 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 <typename T> T a; };", which you cannot. Commented Jan 11, 2014 at 6:22
  • @Kerrek SB I was referring to something like the very first example here, or the question here, but using the boost::function Commented Jan 11, 2014 at 7:34

1 Answer 1

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++.

Sign up to request clarification or add additional context in comments.

2 Comments

Ok, so the point is: class methods can be templatized (like here), 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?
@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 <void (const T)> test_fun; to be an object, which cannot be templatized.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.