在编译时检查类构造函数签名

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).

这篇关于在编译时检查类构造函数签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在编译时检查类构造函数签名

基础教程推荐