确定类是否实现了operator()的任何方法
我试图找到是否有一种方法可以检查一个类是否是函数式的,因为我想编写一个使用它的模板?
有没有简单的方法可以做到这一点?或者我只是将东西包装在 try/catch 中?或者也许编译器甚至不会让我这样做?
I'm trying to find is there's a way to check if a class is a functional because i want to write a template which uses it?
Is there an easy way to do this? Or do I just wrap things in a try/catch? Or perhaps the compiler won't even let me do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您有一个函数模板,如下所示:
您将无法使用任何不可作为不带参数的函数调用的类型实例化它(例如,重载不带参数的
operator()
的类类型可作为不带参数的函数调用)。如果您尝试这样做,您会收到编译错误。这是要求实例化模板的类型具有某些属性的最简单方法:编写模板时只需依赖具有这些属性的类型,如果该类型不具有所需属性之一,它将不可能用该类型实例化模板。
If you have a function template written like:
you will be unable to instantiate it with any type that is not callable as a function taking no arguments (e.g., a class type that overloads
operator()
taking no arguments is callable as a function that takes no arguments). You would get a compilation error if you tried to do so.This is the simplest way to require the type with which a template is instantiated to have certain properties: just rely on the type having those properties when you write the template, and if the type doesn't have one of the required properties, it will be impossible to instantiate the template with that type.
参数类型可以通过多种方式应用于调用语法
当前的 C++ 无法检查 2.,因此您无需检查,就像其他答案所解释的那样。
There are quite a few ways a parameter type can be applicable to the call syntax
The current C++ cannot check for 2., so you are left without checking, like the other answers explain.
这将属于执行此操作并出现编译错误的情况。编译代码时,模板函数或模板类会针对所使用的类型进行扩展,就好像该模板代码有重复副本一样,每种类型都有一个副本。
因此,您基本上可以做任何事情,只要模板使用的所有类型都支持它,就没有问题。如果他们不支持它,您就会遇到编译错误,并且在不修复它的情况下无法运行代码。
This would fall under doing it and getting a compiling error. When the code is compiled the template function or template classes are are expanded for the types used as if there were duplicate copies of that template code, one for each type.
So you can basically do whatever and as long as all the types used for your templates support it you have no problem. If they don't support it you have a compiling error and you can't run your code without fixing it.
如果您实际上需要测试来查看类型 T 是否实现了某个给定签名的operator(),那么您可以使用用于识别此处讨论的任何其他类成员是否存在的相同 SFINAE 技巧:C++“if then else”模板替换
If you actually need a test to see if type T implements an operator() of some given signature then you could use the same SFINAE trick used to identify the existence of any other class member that is discussed here: C++ "if then else" template substitution