检查类是否具有给定签名的成员函数

时间:2008-09-17 20:36:43

标签: c++ c++11 templates sfinae

我要求一个模板技巧来检测一个类是否具有给定签名的特定成员函数。

问题类似于此处引用的问题 http://www.gotw.ca/gotw/071.htm 但不一样:在Sutter的书中,他回答了一个问题,即C类必须提供具有特定签名的成员函数,否则程序将无法编译。在我的问题中,我需要做一些事情,如果一个类有这个功能,否则做“其他”。

boost :: serialization面临类似的问题,但我不喜欢他们采用的解决方案:模板函数默认调用具有特定签名的自由函数(您必须定义),除非您定义特定的使用特定签名的成员函数(在它们的情况下为“serialize”,它接受给定类型的2个参数),否则将发生编译错误。那就是实现侵入式和非侵入式序列化。

我不喜欢这个解决方案有两个原因:

  1. 要非侵入性,您必须覆盖boost :: serialization命名空间中的全局“序列化”函数,因此您可以在您的客户端代码中打开命名空间提升和命名空间序列化!
  2. 要解决此问题的堆栈 乱七八糟的功能调用。
  3. 我需要为没有该成员函数的类定义自定义行为,并且我的实体位于不同的名称空间内(我不想覆盖在另一个名称空间中定义的全局函数)

    你能给我一个解决这个难题的提示吗?

18 个答案:

答案 0 :(得分:113)

这是一种依赖于C ++ 11功能的可能实现。它正确地检测了函数,即使它是继承的(与接受的答案中的解决方案不同,正如Mike Kinghan在his answer中观察到的那样)。

此代码段测试的功能称为serialize

#include <type_traits>

// Primary template with a static assertion
// for a meaningful error message
// if it ever gets instantiated.
// We could leave it undefined if we didn't care.

template<typename, typename T>
struct has_serialize {
    static_assert(
        std::integral_constant<T, false>::value,
        "Second template parameter needs to be of function type.");
};

// specialization that does the checking

template<typename C, typename Ret, typename... Args>
struct has_serialize<C, Ret(Args...)> {
private:
    template<typename T>
    static constexpr auto check(T*)
    -> typename
        std::is_same<
            decltype( std::declval<T>().serialize( std::declval<Args>()... ) ),
            Ret    // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        >::type;  // attempt to call it and see if the return type is correct

    template<typename>
    static constexpr std::false_type check(...);

    typedef decltype(check<C>(0)) type;

public:
    static constexpr bool value = type::value;
};

用法:

struct X {
     int serialize(const std::string&) { return 42; } 
};

struct Y : X {};

std::cout << has_serialize<Y, int(const std::string&)>::value; // will print 1

答案 1 :(得分:86)

我不确定我是否理解正确,但您可以利用SFINAE在编译时检测功能存在。我的代码示例(测试类是否具有成员函数size_t used_memory()const)。

template<typename T>
struct HasUsedMemoryMethod
{
    template<typename U, size_t (U::*)() const> struct SFINAE {};
    template<typename U> static char Test(SFINAE<U, &U::used_memory>*);
    template<typename U> static int Test(...);
    static const bool Has = sizeof(Test<T>(0)) == sizeof(char);
};

template<typename TMap>
void ReportMemUsage(const TMap& m, std::true_type)
{
        // We may call used_memory() on m here.
}
template<typename TMap>
void ReportMemUsage(const TMap&, std::false_type)
{
}
template<typename TMap>
void ReportMemUsage(const TMap& m)
{
    ReportMemUsage(m, 
        std::integral_constant<bool, HasUsedMemoryMethod<TMap>::Has>());
}

答案 2 :(得分:35)

这个compiletime成员函数问题的接受答案 虽然它很受欢迎,但内省有一个可以观察到的障碍 在以下程序中:

#include <type_traits>
#include <iostream>
#include <memory>

/*  Here we apply the accepted answer's technique to probe for the
    the existence of `E T::operator*() const`
*/
template<typename T, typename E>
struct has_const_reference_op
{
    template<typename U, E (U::*)() const> struct SFINAE {};
    template<typename U> static char Test(SFINAE<U, &U::operator*>*);
    template<typename U> static int Test(...);
    static const bool value = sizeof(Test<T>(0)) == sizeof(char);
};

using namespace std;

/* Here we test the `std::` smart pointer templates, including the
    deprecated `auto_ptr<T>`, to determine in each case whether
    T = (the template instantiated for `int`) provides 
    `int & T::operator*() const` - which all of them in fact do.
*/ 
int main(void)
{
    cout << has_const_reference_op<auto_ptr<int>,int &>::value;
    cout << has_const_reference_op<unique_ptr<int>,int &>::value;
    cout << has_const_reference_op<shared_ptr<int>,int &>::value << endl;
    return 0;
}

使用GCC 4.6.3构建,程序输出110 - 通知我们 T = std::shared_ptr<int> 提供int & T::operator*() const

如果你还不熟悉这个问题,那么看看它的定义 标题std::shared_ptr<T>中的<memory>将会显露出来。在那里面 实现,std::shared_ptr<T>派生自基类 从中继承operator*() const。所以模板实例化 构成“寻找”运营商的SFINAE<U, &U::operator*> U = std::shared_ptr<T>不会发生std::shared_ptr<T>,因为operator*()没有 T本身就是mf,而模板实例化却没有 “继承”。

这个障碍不会影响着名的SFINAE方法,使用“The sizeof()Trick”, 仅用于检测T::mf是否具有某个成员函数&T::mf(参见例如 this answer和评论)。但 确定T::mf存在通常(通常是?)不够好:你可以 还需要确定它具有所需的签名。那就是 插图技术分数。所需签名的指针变体 被刻在必须满足的模板类型的参数中 T::mf让SFINAE探测成功。但是这个模板实例化了 当&T::mf被继承时,技术会给出错误的答案。

用于E T::operator*() const的编译时内省的安全SFINAE技术必须避免使用 在模板参数中使用T来实例化SFINAE上的类型 功能模板分辨率取决于相反,SFINAE模板功能 分辨率只能取决于所使用的完全相关的类型声明 作为重载SFINAE探测函数的参数类型。

通过对这个约束的问题的回答,我会 说明E的编译时检测 任意#include <type_traits> /*! The template `has_const_reference_op<T,E>` exports a boolean constant `value that is true iff `T` provides `E T::operator*() const` */ template< typename T, typename E> struct has_const_reference_op { /* SFINAE operator-has-correct-sig :) */ template<typename A> static std::true_type test(E (A::*)() const) { return std::true_type(); } /* SFINAE operator-exists :) */ template <typename A> static decltype(test(&A::operator*)) test(decltype(&A::operator*),void *) { /* Operator exists. What about sig? */ typedef decltype(test(&A::operator*)) return_type; return return_type(); } /* SFINAE game over :( */ template<typename A> static std::false_type test(...) { return std::false_type(); } /* This will be either `std::true_type` or `std::false_type` */ typedef decltype(test<T>(0,0)) type; static const bool value = type::value; /* Which is it? */ }; test()。相同的模式将适用于 mutatis mutandis 探测任何其他成员方法签名。

T::operator*()

在此解决方案中,“调用过载的SFINAE探测函数T::operator*() 递归“。(当然它实际上根本没有被调用;它只是有 由编译器解决的假设调用的返回类型。)

我们需要探测至少一个,最多两个信息点:

  • E T::operator*() const是否存在?如果没有,我们就完成了。
  • 鉴于test(0,0)存在,是它的签名 typedef decltype(test<T>(0,0)) type;

我们通过评估单个呼叫的返回类型来获得答案 到/* SFINAE operator-exists :) */。这是通过以下方式完成的:

test()

此调用可能会解决为/* SFINAE game over :( */重载 /* SFINAE operator-has-correct-sig :) */的{​​{1}},或者它可能会解决/* SFINAE operator-has-correct-sig :) */超载。 它无法解决test(0,0)重载, 因为那个人只想要一个参数而我们正在传递两个参数。

为什么我们通过两个?只需强制解析即可排除 /* SFINAE operator-exists :) */。第二个论点没有其他意义。

decltype(&A::operator*)的来电将仅解析为A = T 如果第一个参数0满足该重载的第一个参数类型, 这是T::operator*/* SFINAE operator-exists :) */。 0将满足该类型 以防decltype(test(&A::operator*))存在。

让我们假设编译器对此说“是”。然后就开始了 test()并且需要确定返回类型 函数调用,在这种情况下是&A::operator* - 另一次调用test(&A::operator*)的返回类型。

这一次,我们只传递了一个参数/* SFINAE operator-has-correct-sig :) */,我们现在就这样做了 知道存在,或者我们不会在这里。拨打/* SFINAE game over :( */可能会 解析为/* SFINAE operator-has-correct-sig :) */或再次解决 可能会解析为&A::operator*。通话将匹配 E (A::*)() const以防A = T满足 该重载的单个参数类型,即T::operator*, 与std::true_type

如果/* SFINAE operator-exists :) */具有所需的签名,编译器会在此处说“是”, 然后再次必须评估过载的返回类型。不再 现在是“递归”:它是test(0,0)

如果编译器没有选择/* SFINAE operator-has-correct-sig :) */ 致电test(&A::operator*)或不选择/* SFINAE game over :( */ 对于电话std::false_type,那么在任何一种情况下它都会随之而来 // To test struct empty{}; // To test struct int_ref { int & operator*() const { return *_pint; } int & foo() const { return *_pint; } int * _pint; }; // To test struct sub_int_ref : int_ref{}; // To test template<typename E> struct ee_ref { E & operator*() { return *_pe; } E & foo() const { return *_pe; } E * _pe; }; // To test struct sub_ee_ref : ee_ref<char>{}; using namespace std; #include <iostream> #include <memory> #include <vector> int main(void) { cout << "Expect Yes" << endl; cout << has_const_reference_op<auto_ptr<int>,int &>::value; cout << has_const_reference_op<unique_ptr<int>,int &>::value; cout << has_const_reference_op<shared_ptr<int>,int &>::value; cout << has_const_reference_op<std::vector<int>::iterator,int &>::value; cout << has_const_reference_op<std::vector<int>::const_iterator, int const &>::value; cout << has_const_reference_op<int_ref,int &>::value; cout << has_const_reference_op<sub_int_ref,int &>::value << endl; cout << "Expect No" << endl; cout << has_const_reference_op<int *,int &>::value; cout << has_const_reference_op<unique_ptr<int>,char &>::value; cout << has_const_reference_op<unique_ptr<int>,int const &>::value; cout << has_const_reference_op<unique_ptr<int>,int>::value; cout << has_const_reference_op<unique_ptr<long>,int &>::value; cout << has_const_reference_op<int,int>::value; cout << has_const_reference_op<std::vector<int>,int &>::value; cout << has_const_reference_op<ee_ref<int>,int &>::value; cout << has_const_reference_op<sub_ee_ref,int &>::value; cout << has_const_reference_op<empty,int &>::value << endl; return 0; } ,最终返回类型为{{1}}。

这是一个测试程序,显示产生预期的模板 不同案例样本的答案(GCC 4.6.3再次)。

{{1}}

这个想法有新的缺陷吗?如果不再一次,它可以变得更通用吗? 它避免了陷阱的犯规?

答案 3 :(得分:12)

以下是一些使用情况摘要: *所有这些的胆量更远

检查给定班级中的成员x。可以是var,func,class,union或enum:

CREATE_MEMBER_CHECK(x);
bool has_x = has_member_x<class_to_check_for_x>::value;

检查成员函数void x()

//Func signature MUST have T as template variable here... simpler this way :\
CREATE_MEMBER_FUNC_SIG_CHECK(x, void (T::*)(), void__x);
bool has_func_sig_void__x = has_member_func_void__x<class_to_check_for_x>::value;

检查成员变量x

CREATE_MEMBER_VAR_CHECK(x);
bool has_var_x = has_member_var_x<class_to_check_for_x>::value;

检查会员班级x

CREATE_MEMBER_CLASS_CHECK(x);
bool has_class_x = has_member_class_x<class_to_check_for_x>::value;

检查成员联盟x

CREATE_MEMBER_UNION_CHECK(x);
bool has_union_x = has_member_union_x<class_to_check_for_x>::value;

检查成员枚举x

CREATE_MEMBER_ENUM_CHECK(x);
bool has_enum_x = has_member_enum_x<class_to_check_for_x>::value;

检查任何成员函数x,无论签名如何:

CREATE_MEMBER_CHECK(x);
CREATE_MEMBER_VAR_CHECK(x);
CREATE_MEMBER_CLASS_CHECK(x);
CREATE_MEMBER_UNION_CHECK(x);
CREATE_MEMBER_ENUM_CHECK(x);
CREATE_MEMBER_FUNC_CHECK(x);
bool has_any_func_x = has_member_func_x<class_to_check_for_x>::value;

OR

CREATE_MEMBER_CHECKS(x);  //Just stamps out the same macro calls as above.
bool has_any_func_x = has_member_func_x<class_to_check_for_x>::value;

详细信息和核心:

/*
    - Multiple inheritance forces ambiguity of member names.
    - SFINAE is used to make aliases to member names.
    - Expression SFINAE is used in just one generic has_member that can accept
      any alias we pass it.
*/

//Variadic to force ambiguity of class members.  C++11 and up.
template <typename... Args> struct ambiguate : public Args... {};

//Non-variadic version of the line above.
//template <typename A, typename B> struct ambiguate : public A, public B {};

template<typename A, typename = void>
struct got_type : std::false_type {};

template<typename A>
struct got_type<A> : std::true_type {
    typedef A type;
};

template<typename T, T>
struct sig_check : std::true_type {};

template<typename Alias, typename AmbiguitySeed>
struct has_member {
    template<typename C> static char ((&f(decltype(&C::value))))[1];
    template<typename C> static char ((&f(...)))[2];

    //Make sure the member name is consistently spelled the same.
    static_assert(
        (sizeof(f<AmbiguitySeed>(0)) == 1)
        , "Member name specified in AmbiguitySeed is different from member name specified in Alias, or wrong Alias/AmbiguitySeed has been specified."
    );

    static bool const value = sizeof(f<Alias>(0)) == 2;
};

宏(El Diablo!):

<强> CREATE_MEMBER_CHECK:

//Check for any member with given name, whether var, func, class, union, enum.
#define CREATE_MEMBER_CHECK(member)                                         \
                                                                            \
template<typename T, typename = std::true_type>                             \
struct Alias_##member;                                                      \
                                                                            \
template<typename T>                                                        \
struct Alias_##member <                                                     \
    T, std::integral_constant<bool, got_type<decltype(&T::member)>::value>  \
> { static const decltype(&T::member) value; };                             \
                                                                            \
struct AmbiguitySeed_##member { char member; };                             \
                                                                            \
template<typename T>                                                        \
struct has_member_##member {                                                \
    static const bool value                                                 \
        = has_member<                                                       \
            Alias_##member<ambiguate<T, AmbiguitySeed_##member>>            \
            , Alias_##member<AmbiguitySeed_##member>                        \
        >::value                                                            \
    ;                                                                       \
}

<强> CREATE_MEMBER_VAR_CHECK:

//Check for member variable with given name.
#define CREATE_MEMBER_VAR_CHECK(var_name)                                   \
                                                                            \
template<typename T, typename = std::true_type>                             \
struct has_member_var_##var_name : std::false_type {};                      \
                                                                            \
template<typename T>                                                        \
struct has_member_var_##var_name<                                           \
    T                                                                       \
    , std::integral_constant<                                               \
        bool                                                                \
        , !std::is_member_function_pointer<decltype(&T::var_name)>::value   \
    >                                                                       \
> : std::true_type {}

<强> CREATE_MEMBER_FUNC_SIG_CHECK:

//Check for member function with given name AND signature.
#define CREATE_MEMBER_FUNC_SIG_CHECK(func_name, func_sig, templ_postfix)    \
                                                                            \
template<typename T, typename = std::true_type>                             \
struct has_member_func_##templ_postfix : std::false_type {};                \
                                                                            \
template<typename T>                                                        \
struct has_member_func_##templ_postfix<                                     \
    T, std::integral_constant<                                              \
        bool                                                                \
        , sig_check<func_sig, &T::func_name>::value                         \
    >                                                                       \
> : std::true_type {}

<强> CREATE_MEMBER_CLASS_CHECK:

//Check for member class with given name.
#define CREATE_MEMBER_CLASS_CHECK(class_name)               \
                                                            \
template<typename T, typename = std::true_type>             \
struct has_member_class_##class_name : std::false_type {};  \
                                                            \
template<typename T>                                        \
struct has_member_class_##class_name<                       \
    T                                                       \
    , std::integral_constant<                               \
        bool                                                \
        , std::is_class<                                    \
            typename got_type<typename T::class_name>::type \
        >::value                                            \
    >                                                       \
> : std::true_type {}

<强> CREATE_MEMBER_UNION_CHECK:

//Check for member union with given name.
#define CREATE_MEMBER_UNION_CHECK(union_name)               \
                                                            \
template<typename T, typename = std::true_type>             \
struct has_member_union_##union_name : std::false_type {};  \
                                                            \
template<typename T>                                        \
struct has_member_union_##union_name<                       \
    T                                                       \
    , std::integral_constant<                               \
        bool                                                \
        , std::is_union<                                    \
            typename got_type<typename T::union_name>::type \
        >::value                                            \
    >                                                       \
> : std::true_type {}

<强> CREATE_MEMBER_ENUM_CHECK:

//Check for member enum with given name.
#define CREATE_MEMBER_ENUM_CHECK(enum_name)                 \
                                                            \
template<typename T, typename = std::true_type>             \
struct has_member_enum_##enum_name : std::false_type {};    \
                                                            \
template<typename T>                                        \
struct has_member_enum_##enum_name<                         \
    T                                                       \
    , std::integral_constant<                               \
        bool                                                \
        , std::is_enum<                                     \
            typename got_type<typename T::enum_name>::type  \
        >::value                                            \
    >                                                       \
> : std::true_type {}

<强> CREATE_MEMBER_FUNC_CHECK:

//Check for function with given name, any signature.
#define CREATE_MEMBER_FUNC_CHECK(func)          \
template<typename T>                            \
struct has_member_func_##func {                 \
    static const bool value                     \
        = has_member_##func<T>::value           \
        && !has_member_var_##func<T>::value     \
        && !has_member_class_##func<T>::value   \
        && !has_member_union_##func<T>::value   \
        && !has_member_enum_##func<T>::value    \
    ;                                           \
}

<强> CREATE_MEMBER_CHECKS:

//Create all the checks for one member.  Does NOT include func sig checks.
#define CREATE_MEMBER_CHECKS(member)    \
CREATE_MEMBER_CHECK(member);            \
CREATE_MEMBER_VAR_CHECK(member);        \
CREATE_MEMBER_CLASS_CHECK(member);      \
CREATE_MEMBER_UNION_CHECK(member);      \
CREATE_MEMBER_ENUM_CHECK(member);       \
CREATE_MEMBER_FUNC_CHECK(member)

答案 4 :(得分:11)

如果你知道你期望的成员函数的名称,那就足够了。 (在这种情况下,如果没有成员函数,函数bla无法实例化(编写一个无论如何都很难,因为缺少函数部分特化。你可能需要使用类模板)另外,启用结构(这个类似于enable_if)也可以模仿你希望它作为成员的函数类型。

template <typename T, int (T::*) ()> struct enable { typedef T type; };
template <typename T> typename enable<T, &T::i>::type bla (T&);
struct A { void i(); };
struct B { int i(); };
int main()
{
  A a;
  B b;
  bla(b);
  bla(a);
}

答案 5 :(得分:5)

以下是Mike Kinghan的回答。这将检测继承的方法。它还会检查完全签名(与jrok的允许参数转换的方法不同)。

template <class C>
class HasGreetMethod
{
    template <class T>
    static std::true_type testSignature(void (T::*)(const char*) const);

    template <class T>
    static decltype(testSignature(&T::greet)) test(std::nullptr_t);

    template <class T>
    static std::false_type test(...);

public:
    using type = decltype(test<C>(nullptr));
    static const bool value = type::value;
};

struct A { void greet(const char* name) const; };
struct Derived : A { };
static_assert(HasGreetMethod<Derived>::value, "");

Runnable example

答案 6 :(得分:4)

您可以使用 std::is_member_function_pointer

class A {
   public:
     void foo() {};
}

 bool test = std::is_member_function_pointer<decltype(&A::foo)>::value;

答案 7 :(得分:4)

我自己也遇到了同样的问题,并且发现这里提出的解决方案非常有趣......但是需要一个解决方案:

  1. 也检测继承的函数;
  2. 与非C ++ 11就绪编译器兼容(因此没有decltype)
  3. 根据thread找到另一个BOOST discussion建议这样的内容。 以下是所提出的解决方案的概括,作为traits类的两个宏声明,遵循boost::has_*类的模型。

    #include <boost/type_traits/is_class.hpp>
    #include <boost/mpl/vector.hpp>
    
    /// Has constant function
    /** \param func_ret_type Function return type
        \param func_name Function name
        \param ... Variadic arguments are for the function parameters
    */
    #define DECLARE_TRAITS_HAS_FUNC_C(func_ret_type, func_name, ...) \
        __DECLARE_TRAITS_HAS_FUNC(1, func_ret_type, func_name, ##__VA_ARGS__)
    
    /// Has non-const function
    /** \param func_ret_type Function return type
        \param func_name Function name
        \param ... Variadic arguments are for the function parameters
    */
    #define DECLARE_TRAITS_HAS_FUNC(func_ret_type, func_name, ...) \
        __DECLARE_TRAITS_HAS_FUNC(0, func_ret_type, func_name, ##__VA_ARGS__)
    
    // Traits content
    #define __DECLARE_TRAITS_HAS_FUNC(func_const, func_ret_type, func_name, ...)  \
        template                                                                  \
        <   typename Type,                                                        \
            bool is_class = boost::is_class<Type>::value                          \
        >                                                                         \
        class has_func_ ## func_name;                                             \
        template<typename Type>                                                   \
        class has_func_ ## func_name<Type,false>                                  \
        {public:                                                                  \
            BOOST_STATIC_CONSTANT( bool, value = false );                         \
            typedef boost::false_type type;                                       \
        };                                                                        \
        template<typename Type>                                                   \
        class has_func_ ## func_name<Type,true>                                   \
        {   struct yes { char _foo; };                                            \
            struct no { yes _foo[2]; };                                           \
            struct Fallback                                                       \
            {   func_ret_type func_name( __VA_ARGS__ )                            \
                    UTILITY_OPTIONAL(func_const,const) {}                         \
            };                                                                    \
            struct Derived : public Type, public Fallback {};                     \
            template <typename T, T t>  class Helper{};                           \
            template <typename U>                                                 \
            static no deduce(U*, Helper                                           \
                <   func_ret_type (Fallback::*)( __VA_ARGS__ )                    \
                        UTILITY_OPTIONAL(func_const,const),                       \
                    &U::func_name                                                 \
                >* = 0                                                            \
            );                                                                    \
            static yes deduce(...);                                               \
        public:                                                                   \
            BOOST_STATIC_CONSTANT(                                                \
                bool,                                                             \
                value = sizeof(yes)                                               \
                    == sizeof( deduce( static_cast<Derived*>(0) ) )               \
            );                                                                    \
            typedef ::boost::integral_constant<bool,value> type;                  \
            BOOST_STATIC_CONSTANT(bool, is_const = func_const);                   \
            typedef func_ret_type return_type;                                    \
            typedef ::boost::mpl::vector< __VA_ARGS__ > args_type;                \
        }
    
    // Utility functions
    #define UTILITY_OPTIONAL(condition, ...) UTILITY_INDIRECT_CALL( __UTILITY_OPTIONAL_ ## condition , ##__VA_ARGS__ )
    #define UTILITY_INDIRECT_CALL(macro, ...) macro ( __VA_ARGS__ )
    #define __UTILITY_OPTIONAL_0(...)
    #define __UTILITY_OPTIONAL_1(...) __VA_ARGS__
    

    这些宏使用以下原型扩展到traits类:

    template<class T>
    class has_func_[func_name]
    {
    public:
        /// Function definition result value
        /** Tells if the tested function is defined for type T or not.
        */
        static const bool value = true | false;
    
        /// Function definition result type
        /** Type representing the value attribute usable in
            http://www.boost.org/doc/libs/1_53_0/libs/utility/enable_if.html
        */
        typedef boost::integral_constant<bool,value> type;
    
        /// Tested function constness indicator
        /** Indicates if the tested function is const or not.
            This value is not deduced, it is forced depending
            on the user call to one of the traits generators.
        */
        static const bool is_const = true | false;
    
        /// Tested function return type
        /** Indicates the return type of the tested function.
            This value is not deduced, it is forced depending
            on the user's arguments to the traits generators.
        */
        typedef func_ret_type return_type;
    
        /// Tested function arguments types
        /** Indicates the arguments types of the tested function.
            This value is not deduced, it is forced depending
            on the user's arguments to the traits generators.
        */
        typedef ::boost::mpl::vector< __VA_ARGS__ > args_type;
    };
    

    那么人们可以做的典型用法是什么呢?

    // We enclose the traits class into
    // a namespace to avoid collisions
    namespace ns_0 {
        // Next line will declare the traits class
        // to detect the member function void foo(int,int) const
        DECLARE_TRAITS_HAS_FUNC_C(void, foo, int, int);
    }
    
    // we can use BOOST to help in using the traits
    #include <boost/utility/enable_if.hpp>
    
    // Here is a function that is active for types
    // declaring the good member function
    template<typename T> inline
    typename boost::enable_if< ns_0::has_func_foo<T> >::type
    foo_bar(const T &_this_, int a=0, int b=1)
    {   _this_.foo(a,b);
    }
    
    // Here is a function that is active for types
    // NOT declaring the good member function
    template<typename T> inline
    typename boost::disable_if< ns_0::has_func_foo<T> >::type
    foo_bar(const T &_this_, int a=0, int b=1)
    {   default_foo(_this_,a,b);
    }
    
    // Let us declare test types
    struct empty
    {
    };
    struct direct_foo
    {
        void foo(int,int);
    };
    struct direct_const_foo
    {
        void foo(int,int) const;
    };
    struct inherited_const_foo :
        public direct_const_foo
    {
    };
    
    // Now anywhere in your code you can seamlessly use
    // the foo_bar function on any object:
    void test()
    {
        int a;
        foo_bar(a); // calls default_foo
    
        empty b;
        foo_bar(b); // calls default_foo
    
        direct_foo c;
        foo_bar(c); // calls default_foo (member function is not const)
    
        direct_const_foo d;
        foo_bar(d); // calls d.foo (member function is const)
    
        inherited_const_foo e;
        foo_bar(e); // calls e.foo (inherited member function)
    }
    

答案 8 :(得分:4)

要实现这一目标,我们需要使用:

    根据方法是否可用,
  1. Function template overloading具有不同的返回类型
  2. 为了与type_traits标题中的元条件保持一致,我们希望从过载中返回true_type or false_type
  3. 声明true_type重载期望intfalse_type重载期望可变参数利用:"The lowest priority of the ellipsis conversion in overload resolution"
  4. 在定义true_type函数的模板规范时,我们将使用declvaldecltype,允许我们检测函数,而不依赖于返回类型差异或方法之间的重载
  5. 您可以看到此here的实际示例。但我也会在下面解释:

    我想检查是否存在名为test的函数,该函数采用可转换为int的类型,然后我需要声明这两个函数:

    template <typename T, typename S = decltype(declval<T>().test(declval<int>))> static true_type hasTest(int);
    template <typename T> static false_type hasTest(...);
    
    • decltype(hasTest<a>(0))::valuetrue(请注意,无需创建特殊功能来处理void a::test()重载,void a::test(int)已被接受)
    • decltype(hasTest<b>(0))::valuetrue(由于int可转换为double int b::test(double),因此可以接受,与返回类型无关)
    • decltype(hasTest<c>(0))::valuefalsec没有名为test的方法,该方法接受可从int转换的类型,因此不接受此选项)

    此解决方案有两个缺点:

    1. 需要一对函数的每方法声明
    2. 特别是如果我们要测试相似的名称,就会创建命名空间污染,例如,我们将一个想要测试test()方法的函数命名为什么?
    3. 因此,在细节命名空间中声明这些函数非常重要,或者理想情况下,如果它们只用于类,则它们应该由该类私有声明。为此,我编写了一个宏来帮助您抽象出这些信息:

      #define FOO(FUNCTION, DEFINE) template <typename T, typename S = decltype(declval<T>().FUNCTION)> static true_type __ ## DEFINE(int); \
                                    template <typename T> static false_type __ ## DEFINE(...); \
                                    template <typename T> using DEFINE = decltype(__ ## DEFINE<T>(0));
      

      你可以使用它:

      namespace details {
          FOO(test(declval<int>()), test_int)
          FOO(test(), test_void)
      }
      

      随后调用details::test_int<a>::valuedetails::test_void<a>::value会产生truefalse,以用于内联代码或元编程。

答案 9 :(得分:3)

要进行非侵入式,您还可以将serialize放入要序列化的类的名称空间中,或归档到归档类,这要归功于Koenig lookup。有关详细信息,请参阅Namespaces for Free Function Overrides。 : - )

打开任何给定的命名空间来实现自由功能是完全错误的。 (例如,您不应该打开名称空间std来为您自己的类型实现swap,但应该使用Koenig查找。)

答案 10 :(得分:3)

您似乎想要检测器惯用语。上面的答案是与C ++ 11或C ++ 14一起工作的变体。

std::experimental库具有本质上可以做到这一点的功能。从上面重做一个示例,可能是:

#include <experimental/type_traits>

// serialized_method_t is a detector type for T.serialize(int) const
template<typename T>
using serialized_method_t = decltype(std::declval<const T&>.serialize(std::declval<int>()));

// has_serialize_t is std::true_type when T.serialize(int) exists,
// and false otherwise.
template<typename T>
using has_serialize_t = std::experimental::is_detected_t<serialized_method_t, T>;

如果您不能使用std :: experimental,则可以制作一个基本的版本:

template <typename... Ts>
using void_t = void;
template <template <class...> class Trait, class AlwaysVoid, class... Args>
struct detector : std::false_type {};
template <template <class...> class Trait, class... Args>
struct detector<Trait, void_t<Trait<Args...>>, Args...> : std::true_type {};

// serialized_method_t is a detector type for T.serialize(int) const
template<typename T>
using serialized_method_t = decltype(std::declval<const T&>.serialize(std::declval<int>()));

// has_serialize_t is std::true_type when T.serialize(int) exists,
// and false otherwise.
template <typename T>
using has_serialize_t = typename detector<serialized_method_t, void, T>::type;

由于has_serialize_t实际上是std :: true_type或std :: false_type,因此可以通过任何常见的SFINAE惯用法来使用它:

template<class T>
std::enable_if_t<has_serialize_t<T>::value, std::string>
SerializeToString(const T& t) {
}

或者通过使用具有超载分辨率的分派:

template<class T>
std::string SerializeImpl(std::true_type, const T& t) {
  // call serialize here.
}

template<class T>
std::string SerializeImpl(std::false_type, const T& t) {
  // do something else here.
}

template<class T>
std::string Serialize(const T& t) {
  return SerializeImpl(has_serialize_t<T>{}, t);
}

答案 11 :(得分:2)

好。第二次尝试。如果你不喜欢这个也没关系,我正在寻找更多的想法。

Herb Sutter的文章讨论了特征。因此,您可以拥有一个traits类,其默认实例化具有回退行为,对于存在成员函数的每个类,traits类专门用于调用成员函数。我相信Herb的文章提到了一种技术来做到这一点,所以它不涉及大量的复制和粘贴。

就像我说的那样,也许你不希望额外的工作涉及“标记”实现该成员的类。在这种情况下,我正在寻找第三种解决方案......

答案 12 :(得分:1)

如果没有C ++ 11支持(decltype),这可能有效:

SSCCE

#include <iostream>
using namespace std;

struct A { void foo(void); };
struct Aa: public A { };
struct B { };

struct retA { int foo(void); };
struct argA { void foo(double); };
struct constA { void foo(void) const; };
struct varA { int foo; };

template<typename T>
struct FooFinder {
    typedef char true_type[1];
    typedef char false_type[2];

    template<int>
    struct TypeSink;

    template<class U>
    static true_type &match(U);

    template<class U>
    static true_type &test(TypeSink<sizeof( matchType<void (U::*)(void)>( &U::foo ) )> *);

    template<class U>
    static false_type &test(...);

    enum { value = (sizeof(test<T>(0, 0)) == sizeof(true_type)) };
};

int main() {
    cout << FooFinder<A>::value << endl;
    cout << FooFinder<Aa>::value << endl;
    cout << FooFinder<B>::value << endl;

    cout << FooFinder<retA>::value << endl;
    cout << FooFinder<argA>::value << endl;
    cout << FooFinder<constA>::value << endl;
    cout << FooFinder<varA>::value << endl;
}

希望如何运作

AAaB是相关条款,Aa是继承我们正在寻找的成员的特殊条款。

FooFinder true_typefalse_type是对应的C ++ 11类的替代品。同样为了理解模板元编程,它们揭示了SFINAE-sizeof-trick的基础。

TypeSink是一个模板结构,稍后用于将sizeof运算符的整数结果存入模板实例化以形成类型。

match函数是另一种SFINAE模板,没有通用对应物。因此,只有在其参数类型与其专用类型匹配时,才能实例化它。

test函数和枚举声明最终形成了中心SFINAE模式。有一个泛型的使用省略号返回false_type和一个具有更多特定参数的对应物优先。

为了能够使用test的模板参数实例化T函数,必须实例化match函数,因为需要返回类型来实例化TypeSink参数。需要注意的是,&U::foo被包含在函数参数中,在模板参数专门化中引用 not ,因此仍然会继承成员查找。

答案 13 :(得分:1)

我也有类似的需求,所以遇到了这种情况。这里提出了许多有趣/功能强大的解决方案,尽管对于一个特定的需求来说有点长:检测类是否具有带有精确签名的成员函数。因此,我进行了一些阅读/测试,并提出了可能感兴趣的版本。它检测到:

  • 静态成员函数
  • 非静态成员函数
  • 非静态成员函数const

具有精确的签名。由于我不需要捕获任何签名(这需要更复杂的解决方案),因此该套件适合我。它基本上使用了 enable_if_t

struct Foo{ static int sum(int, const double&){return 0;} };
struct Bar{ int calc(int, const double&) {return 1;} };
struct BarConst{ int calc(int, const double&) const {return 1;} };

// Note : second typename can be void or anything, as long as it is consistent with the result of enable_if_t
template<typename T, typename = T> struct has_static_sum : std::false_type {};
template<typename T>
struct has_static_sum<typename T,
                        std::enable_if_t<std::is_same<decltype(T::sum), int(int, const double&)>::value,T> 
                      > : std::true_type {};

template<typename T, typename = T> struct has_calc : std::false_type {};
template<typename T>
struct has_calc <typename T,
                  std::enable_if_t<std::is_same<decltype(&T::calc), int(T::*)(int, const double&)>::value,T>
                > : std::true_type {};

template<typename T, typename = T> struct has_calc_const : std::false_type {};
template<typename T>
struct has_calc_const <T,
                        std::enable_if_t<std::is_same<decltype(&T::calc), int(T::*)(int, const double&) const>::value,T>
                      > : std::true_type {};

int main ()
{
    constexpr bool has_sum_val = has_static_sum<Foo>::value;
    constexpr bool not_has_sum_val = !has_static_sum<Bar>::value;

    constexpr bool has_calc_val = has_calc<Bar>::value;
    constexpr bool not_has_calc_val = !has_calc<Foo>::value;

    constexpr bool has_calc_const_val = has_calc_const<BarConst>::value;
    constexpr bool not_has_calc_const_val = !has_calc_const<Bar>::value;

    std::cout<< "           has_sum_val " << has_sum_val            << std::endl
             << "       not_has_sum_val " << not_has_sum_val        << std::endl
             << "          has_calc_val " << has_calc_val           << std::endl
             << "      not_has_calc_val " << not_has_calc_val       << std::endl
             << "    has_calc_const_val " << has_calc_const_val     << std::endl
             << "not_has_calc_const_val " << not_has_calc_const_val << std::endl;
}

输出:

           has_sum_val 1
       not_has_sum_val 1
          has_calc_val 1
      not_has_calc_val 1
    has_calc_const_val 1
not_has_calc_const_val 1

答案 14 :(得分:0)

如果您使用的是Facebook Folly,则它们是开箱即用的宏,可以帮助您:

#include <folly/Traits.h>
namespace {
  FOLLY_CREATE_HAS_MEMBER_FN_TRAITS(has_test_traits, test);
} // unnamed-namespace

void some_func() {
  cout << "Does class Foo have a member int test() const? "
    << boolalpha << has_test_traits<Foo, int() const>::value;
}

尽管实现细节与上一个答案相同,但是使用库更简单。

答案 15 :(得分:0)

我相信你要找的答案就在这里。

http://www.martinecker.com/wiki/index.php?title=Detecting_the_Existence_of_Operators_at_Compile-Time

这里有一个稍微充实的例子

http://pastie.org/298994

我使用该技术检测相关类上是否存在支持 ostream运算符&lt; ,然后生成不同的代码位。

在找到链接解决方案之前,我不相信这是可能的,但这是一个非常巧妙的技巧。花时间理解代码,这是非常值得的。

布拉德

答案 16 :(得分:0)

jrokanswer为基础,我避免使用嵌套的模板类和/或函数。

#include <type_traits>

#define CHECK_NESTED_FUNC(fName) \
    template <typename, typename, typename = std::void_t<>> \
    struct _has_##fName \
    : public std::false_type {}; \
    \
    template <typename Class, typename Ret, typename... Args> \
    struct _has_##fName<Class, Ret(Args...), \
        std::void_t<decltype(std::declval<Class>().fName(std::declval<Args>()...))>> \
    : public std::is_same<decltype(std::declval<Class>().fName(std::declval<Args>()...)), Ret> \
    {}; \
    \
    template <typename Class, typename Signature> \
    using has_##fName = _has_##fName<Class, Signature>;

#define HAS_NESTED_FUNC(Class, Func, Signature) has_##Func<Class, Signature>::value

我们可以如下使用上述宏:

class Foo
{
public:
    void Bar(int, const char *) {}
};

CHECK_NESTED_FUNC(Bar);  // generate required metafunctions

int main()
{
    using namespace std;
    cout << boolalpha
         << HAS_NESTED_FUNC(Foo, Bar, void(int, const char *))  // prints true
         << endl;
    return 0;
}

欢迎提出建议。

答案 17 :(得分:0)

使用c ++ 20,这变得更加简单。假设我们要测试类T是否具有成员函数void T::resize(typename T::size_type)。例如,std::vector<U>具有这样的成员函数。然后,

template<typename T>
concept has_resize_member_func = requires {
    typename T::size_type;
    { std::declval<T>().resize(std::declval<typename T::size_type>()) } -> std::same_as<void>;
};

用法是

static_assert(has_resize_member_func<std::string>, "");
static_assert(has_resize_member_func<int> == false, "");
相关问题