Вопрос

I'd like to implement a class, which holds two callbacks with pre-defined function signatures.

The class has templated ctor, which uses std::bind to create std::function members. I expected that the compiler (g++ 4.6) would complain if a function with wrong signature is passed to the ctor. However, the compiler accepts the following:

    callback c1(i, &test::func_a, &test::func_a);

I can understand why it does that. I tried to construct a proper condition for static_assert with no 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: Answer from visitor solves my initial problem. Unfortunatelly I have a bunch of related cases to solve, which are demonstrated with 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 visitor is triggered 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 just to compare function arguments and return value. Please suggest how.

Thank you.

Это было полезно?

Решение

You can statically assert in the constructor body:

static_assert(std::is_same<CA, bool(O::*)(const int&)>::value, "First function type incorrect");
static_assert(std::is_same<CB, bool(O::*)(int&)>::value, "Second function type incorrect");

See: http://ideone.com/u0z24

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top