SFINAE成员函数测试说明

时间:2015-12-08 01:28:30

标签: c++ templates sfinae typetraits enable-if

我正在使用以下TypeTrait结构来检测给定方法是否定义了给定方法(具有特定的args)。

template<typename T, typename A>
struct HasSomeMethod
{
    //Simulates a call to a Type with SomeMethod(ArgType&) defined
    template<typename Type, typename ArgType>
    static auto CallMemberMethod(Type& type, ArgType& arg) -> decltype(type.SomeMethod(arg));

    //Will be picked if the above call can succeed
    template<typename Type, typename ArgType>
    static auto Test() -> decltype(CallMemberMethod(std::declval<Type&>(), std::declval<ArgType&>()), std::true_type());

    //Fallback...the Serialize() call failed
    template<typename, typename>
    static std::false_type Test(...);

    //Result of the test
    static const bool value { std::is_same<decltype(Test<T, A>()), std::true_type>::value };
};

我对这是如何工作有一个大概的了解。我不明白的是为什么除了struct本身之外还需要模板化方法。

如:

template<typename T, typename A>
struct HasSomeMethod
{
    static auto CallMemberMethod(T& type, A& arg) -> decltype(type.SomeMethod(arg));

    static auto Test() -> decltype(CallMemberMethod(std::declval<T&>(), std::declval<A&>()), std::true_type());

    static std::false_type Test(...);

    static const bool value { std::is_same<decltype(Test()), std::true_type>::value };
};

这会因编译器错误而失败:ambiguous call to overloaded function

是什么阻止了重复使用已经为方法提供结构的模板类型名?

0 个答案:

没有答案
相关问题