std :: function: rigorosa verifica del tempo di compilazione degli argomenti
-
28-10-2019 - |
Domanda
Vorrei implementare una classe, che contiene due callback con firme di funzione predefinita.
La classe ha un cTOR modello, che utilizza std :: bling per creare membri della funzione std ::. Mi aspettavo che il compilatore (G ++ 4.6) si lamentasse se una funzione con firma errata fosse passata al CTOR. Tuttavia, il compilatore accetta quanto segue:
callback c1(i, &test::func_a, &test::func_a);
Posso capire perché lo fa. Ho provato a costruire una condizione adeguata per static_assert senza successo.
Come posso commettere un errore di compilazione per impedirlo?
#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;
}
AGGIORNARE: Risposta dal visitatore risolve il mio problema iniziale. Sfortunatamente ho un sacco di casi correlati da risolvere, che sono dimostrati con il seguente codice (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 come suggerito dal visitatore viene attivato qui per questo caso, sebbene la firma della funzione sia valida:
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"
Penso che sarebbe meglio solo confrontare gli argomenti della funzione e il valore di ritorno. Si prega di suggerire come.
Grazie.
Soluzione
Puoi affermare staticamente il corpo del costruttore:
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");
Vedere: http://ideone.com/u0z24