I would like to implement a class that contains two callbacks with predefined function signatures.
The class has a templated ctor, which uses std :: bind to create std :: function elements. I expected the compiler (g ++ 4.6) to complain if a function with the wrong signature is passed to ctor. However, the compiler accepts the following:
callback c1(i, &test::func_a, &test::func_a);
I understand why he does it. I tried to build the correct condition for static_assert without success.
How can I make a compile time error to prevent this?
#include <functional> using namespace std::placeholders; class callback { public: typedef std::function<bool(const int&)> type_a; typedef std::function<bool(int&)> type_b; template <class O, typename CA, typename CB> callback(O inst, CA ca, CB cb) : m_ca(std::bind(ca, inst, _1)), m_cb(std::bind(cb, inst, _1)) { } private: type_a m_ca; type_b m_cb; }; class test { public: bool func_a(const int& arg) { return true; } bool func_b(int& arg) { arg = 10; return true; } }; int main() { test i; callback c(i, &test::func_a, &test::func_b); // Both should fail at compile time callback c1(i, &test::func_a, &test::func_a); // callback c2(i, &test::func_b, &test::func_b); return 0; }
UPDATE . A response from the visitor solves my original problem. Unfortunately, I have a bunch of related cases to solve, which are demonstrated using the following code ( http://ideone.com/P32sU ):
class test { public: virtual bool func_a(const int& arg) { return true; } virtual bool func_b(int& arg) { arg = 10; return true; } }; class test_d : public test { public: virtual bool func_b(int& arg) { arg = 20; return true; } }; int main() { test_d i; callback c(i, &test_d::func_a, &test_d::func_b); return 0; }
static_assert, as suggested by the visitor, is run here for this case, although the function signature is valid:
prog.cpp: In constructor 'callback::callback(O, CA, CB) [with O = test_d, CA = bool (test::*)(const int&), CB = bool (test_d::*)(int&)]': prog.cpp:41:51: instantiated from here prog.cpp:17:12: error: static assertion failed: "First function type incorrect"
I think it would be best to compare function arguments and return value. Please suggest how.
Thanks.