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


基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 这个宏可以转换成函数吗? 2022-01-01