我有一个名为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.
更多推荐
发布评论