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)
.
这篇关于在编译时检查类构造函数签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在编译时检查类构造函数签名


- 从python回调到c++的选项 2022-11-16
- STL 中有 dereference_iterator 吗? 2022-01-01
- C++ 协变模板 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 近似搜索的工作原理 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 静态初始化顺序失败 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01