Pregunta

Me gustaría implementar una clase, que contiene dos devoluciones de llamada con firmas de funciones predefinidas.

La clase ha plantado CTOR, que usa std :: bind para crear miembros de la función std ::. Esperaba que el compilador (G ++ 4.6) se quejaría si una función con firma incorrecta se pase al CTOR. Sin embargo, el compilador acepta lo siguiente:

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

Puedo entender por qué hace eso. Traté de construir una condición adecuada para Static_assert sin éxito.

¿Cómo puedo cometer un error de tiempo de compilación para evitar esto?

#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;
}

ACTUALIZAR: La respuesta del visitante resuelve mi problema inicial. Desafortunadamente tengo un montón de casos relacionados para resolver, que se demuestran con el siguiente código (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 según lo sugerido por el visitante se activa aquí para este caso, aunque la firma de la función es válida:

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"

Creo que sería mejor comparar los argumentos de funciones y el valor de retorno. Por favor sugiera cómo.

Gracias.

¿Fue útil?

Solución

Puede afirmar estáticamente en el cuerpo del constructor:

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");

Ver: http://ideone.com/u0z24

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top