如何创建只在其类型具有特定成员函数时才编译的类?(How do I make a class that only compiles when its type has a certain member

编程入门 行业动态 更新时间:2024-10-27 20:32:52
如何创建只在其类型具有特定成员函数时才编译的类?(How do I make a class that only compiles when its type has a certain member function?)

我有一个名为has_f的类,我希望它只接受具有f成员函数的模板参数。 我该怎么办? 这是我试过的:

template <typename T, typename = void> struct has_f : std::false_type {}; template <typename T> struct has_f< T, typename = typename std::enable_if< typename T::f >::type > : std::true_type {};

但我得到了一些神秘的错误。 这是我想要使用的类:

struct A { void f(); };

我该怎么做呢? 谢谢。

I have a class named has_f and I want it to only accept template parameters that have a f member function. How would I do that? This is what I tried:

template <typename T, typename = void> struct has_f : std::false_type {}; template <typename T> struct has_f< T, typename = typename std::enable_if< typename T::f >::type > : std::true_type {};

But I get some cryptic errors. Here is the class I want to use:

struct A { void f(); };

How do I do this correctly? Thanks.

最满意答案

从你的问题的标题我假设你真的不需要从true_type或false_type派生的类型 - 只是为了防止编译,如果方法f不存在。 如果是这种情况,并且如果您还需要该方法的特定签名(至少就参数而言),那么在C ++ 11中,您可以执行以下操作:

template <typename T> struct compile_if_has_f { static const size_t dummy = sizeof( std::add_pointer< decltype(((T*)nullptr)->f()) >::type ); };

这适用于f()不接受任何参数的情况。 仅当f返回void时才需要std :: add_pointer,因为sizeof(void)是非法的。

From the title of your question I presume that you don't really need a type deriving from true_type or false_type - only to prevent compilation if method f is not present. If that is the case, and if you also require a specific signature (at least in terms of arguments) for that method, in C++11 you can do something like this:

template <typename T> struct compile_if_has_f { static const size_t dummy = sizeof( std::add_pointer< decltype(((T*)nullptr)->f()) >::type ); };

This is for the case when f() should not accept any arguments. std::add_pointer is only needed if f returns void, because sizeof(void) is illegal.

更多推荐

本文发布于:2023-08-06 16:29:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1454004.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:只在   时才   函数   成员   类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!