std::function:严格的编译时参数验证
std::function: Strict compile time verification of arguments
我想实现一个类,它包含两个具有预定义函数签名的回调函数。
类有模板化的ctor,它使用std::bind创建std::函数成员。我期望编译器(g++ 4.6)会在将签名错误的函数传递给actor时报错。但是,编译器接受以下内容:
callback c1(i, &test::func_a, &test::func_a);
我能理解它为什么那样做。我尝试为static_assert构造一个合适的条件,但没有成功。
如何使编译时错误来防止这种情况?
#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:来自访问者的答案解决了我最初的问题。不幸的是,我有一堆相关的案例需要解决,下面的代码演示了这些案例(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;
}
对于这种情况,尽管函数签名是有效的,但还是触发了visitor所建议的static_assert:
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"
我认为最好只是比较函数参数和返回值。请告诉我怎么做。
谢谢。
可以在构造函数体中静态断言:
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");
见:http://ideone.com/u0z24
相关文章:
- 如何反转整数参数包
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- boost::p rogram_options 验证每个参数而不是每个参数类型?
- GoogleMock:如何验证输入参数的调用次数?
- 对象验证的模板参数
- 用于验证请求的哈希参数
- 使用constexpr验证构造函数中的文字参数
- GMOCK参数验证
- 随机参数验证
- 处理命令行参数解析/验证的代码段/lib
- CRT参数验证使多线程调试程序崩溃
- 如何验证传递给模拟函数的参数的派生类型
- std::function:严格的编译时参数验证
- 在编译时在c/c++预处理宏中验证参数为ARRAY类型
- 使用"断言"验证参数数
- 正在验证变量参数是否为预期类型