区分不明确的成员请求错误和成员在SFINAE上下文中不存在错误?

时间:2011-06-08 21:11:51

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

编辑:发布了我自己的答案,保留了原来接受的答案......让我思考别名。

编辑:我的问题是针对在SFINAE(或其他)上下文中区分模糊性与成员var / func存在的可能性。我的问题不是关于如何制作一个has_member模板,而是关于检测模糊与存在之间的区别

是否可以设置部分特化,以区分何时以不明确的方式访问成员(派生类的基础都具有成员)vs成员是否存在(派生类的基础都没有会员)?如果检测到歧义,我需要返回true ,但如果根本没有成员,或者只存在一个类,则不需要。这是我到目前为止所返回的,它对于歧义(我想要的)返回true,对于只有一个具有该成员的类(也是我想要的)返回false,但如果两个类都没有该成员,则返回true(argh!)

//for the sake of this example, ClassOne comes from a lib I don't control
struct ClassOne {
    //some unknown members in here... 
};

struct ClassTwo {
    string member_var;
};

template<typename A>
struct helper : std::true_type {};

template<typename A, typename B>
struct merged_class : public A, public B {};

template<typename T, typename = void>
struct has_member_var : std::true_type {
    //Member request ambiguous or neither class has member.
    //I want to catch these conditions separately,
    //but this one template catches both :(
    const int status = 1;
};

template<typename T>
struct has_member_var<
    T
    , typename std::enable_if<
        //The next line results in either ambiguous member request error
        //if both classes have the member OR
        //member does not exist error if neither class has the member
        //...how to tell the difference in the type of error?
        helper<decltype(T::member_var)>::value
        , T
    >::type
> : std::false_type {
    const int status = 2; //only one class has member 
};

//This next one I have no idea how to do, if it's even possible.
//I'd like a third specialization that will match either the
//ambiguous condition or the member only existing in one of the
//base classes.
template<typename T>
struct has_member<
    T
    , typename std::enable_if<
        some_freaky_magic<decltype(T::foo)>::true_value
        , T
    >::type
> : std::true_type {
    const int status = 3;
};

所需用法:

switch(has_member<merged_class<ClassOne, ClassTwo>>::status) {
    case 1:
        cout << "member ambiguity";
        break;
    case 2:
        cout << "member non-existence";
        break;
    case 3:
        cout << "member existence for only one base";
        break;
}

3 个答案:

答案 0 :(得分:6)

好吧,我想我设法采用了expression SFINAE方法并添加了类型扣除。这是一个非常粗暴地被黑客攻击的答案,似乎正在做一些有用的事情(参见底部的用法示例)。

(演示文稿可能会更加简洁和干净,但这样你就会把它分解为几个步骤。)

用法: conflicting_X<A, B>::value当且仅当AB都有一个名为x 的成员且这个成员的类型不同(严格地说,不是腐朽的)。可以使用conflicting_X<A, B>::bothhas_X<T>::value来决定中间问题,例如是否为两个类定义成员。

#include <iostream>
#include <type_traits>
#include <typeinfo>


// has_X is taken straight from the other topic

template <typename T>
struct has_X
{
  struct Fallback { int x; }; // introduce member name "x"
  struct Derived : T, Fallback { };

  template<typename C, C> struct ChT;

  template<typename C> static char (&f(ChT<int Fallback::*, &C::x>*))[1];
  template<typename C> static char (&f(...))[2];

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

// Here we go...

template <typename T>
struct XType
{
  typedef decltype(T::x) type;
};

template <bool, typename S, typename T>
struct compare_X
{
  static const bool value = false;
};

template <typename S, typename T>
struct compare_X<true, S, T>
{
  // Note that we don't decay, we want equality on the nose.
  static const bool value =  ! std::is_same<typename XType<S>::type, typename XType<T>::type>::value;
};

template <typename S, typename T>
struct conflicting_X
{
  // We split this up so that XType is only instantiated if T::x really exists.
  // You may also use conflicting_X::both as a useful datum.
  static const bool both = has_X<S>::value && has_X<T>::value;
  static const bool value = compare_X<both, S, T>::value;
};


/*** Example ***/

struct A { int x; };
struct B { int X; };
struct C { double x; };

void f(double) { }

int main() {
  std::cout << has_X<A>::value << std::endl; // 1
  std::cout << has_X<B>::value << std::endl; // 0

  std::cout << "Conflict A/B? " << conflicting_X<A, B>::value << std::endl;
  std::cout << "Conflict A/C? " << conflicting_X<A, C>::value << std::endl;
}

答案 1 :(得分:2)

更新:我最近使用我在原始答案中发布的代码完成了更多操作,因此我对此进行更新以考虑更改/添加内容。

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

检查给定班级中的成员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.
*/

template <typename... Args> struct ambiguate : public Args... {};

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)

答案 2 :(得分:1)

我不认为这是可能的。要使SFINAE在此处工作,只有当您要查找的成员不明确时,才需要一个或多个特定有效/不良组合的表达式。这假设扩展了SFINAE for C ++ 0x。

但是,给定类型T和潜在(非类型)成员i,可用的表达式是什么? &T::i,如果您仅将案例限制为仅限数据成员,t.i其中t的类型为T

对于这两个表达式,如果i不明确,那么每个表达式都是格式不正确的,但如果它存在且不含糊不清,则每个表达都很好。所以我们无法满足您的要求。

请注意,如果潜在的基数B具有明确的数据成员i,您可以使用&T::it.B::i进行测试。如果第一个表达式格式错误而第二个表达式格式正确,则表示存在不明确的成员i。这是我能达到你要求的最接近的。