Check at compile time class constructor signature(在编译时检查类构造函数签名)
问题描述
有没有办法在编译时检查某个类是否具有带有某些参数的构造函数??
Is there a way to check at compile time if some class has constructor with certain arguments ? ?
例如:
class foo {
foo(std::string &s) {
}
};
我想在编译时用 std::string& 检查构造函数.始终定义.或许 boost 提供了这样的功能?
I want to check at compile time that constructor with std::string& always defined. Maybe boost provides such functionality ?
推荐答案
检查特定函数是否存在的常用方法是获取其地址并将其分配给一个虚拟变量.这比目前提到的测试要精确得多,因为这可以验证确切的函数签名.问题特别是关于签名中的 string& ,因此非常量,因此可能会修改字符串.
The common way to check if a specific function exists is to take its address and assign it to a dummy variable. This is a lot more precise than the tests mentioned so far, because this verifies the exact function signature. And the question was specifically about string& in the signature, so non-const and thus presumably modifying the string.
但是,在这种情况下,您不能使用获取地址并分配它的技巧:构造函数没有地址.那么,你如何检查签名呢?简单地说:在虚拟课程中与它成为朋友.
However, in this case you cannot use the take-the-address-and-assign-it trick: constructors don't have addresses. So, how do you check the signature then? Simply: Befriend it in a dummy class.
template<typename T>
class checkSignature_StringRef {
friend T::T(string&);
};
这也是一个非常具体的检查:它甚至不会匹配类似的构造函数,例如 foo::foo(std::string &s, int dummy = 0).
This too is a very specific check: it will not even match similar constructors like foo::foo(std::string &s, int dummy = 0).
这篇关于在编译时检查类构造函数签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在编译时检查类构造函数签名
基础教程推荐
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- c++ STL设置差异 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
