简体   繁体   中英

Why SFINAE doesn't work?

I want to check that whether the class has operator(). I tryied the following SFINAE.

#include <type_traits>  //for std::true_type/false_type
#include <utility>      //for std::declval

template <typename T, typename... A>
class has_call_operator {
private:
    template <typename U, typename... P>
    static auto check(U u, P... p) -> decltype(u(p...), std::true_type());
    static auto check(...) -> decltype(std::false_type());

public:
    using type
        = decltype(check(std::declval<T>(), std::declval<A>()...));
    static constexpr bool value = type::value;
};

At a glance, this is working correctlly.

#include <iostream>

struct test {
    void operator()(const int x) {}
};

int main()
{
    std::cout << std::boolalpha << has_call_operator<test, int>::value << std::endl;    //true
    return 0;
}

But, the abstract class was not worked correctly by it.

#include <iostream>

struct test {
    void operator()(const int x) {}
    virtual void do_something() = 0;
};

int main()
{
    std::cout << std::boolalpha << has_call_operator<test, int>::value << std::endl;    //false
    return 0;
}

Why does not this code work? Also, could you make this code work?

You take U by value, so it requires also the construction of the type.

Pass by const reference to fix that.

You may look at is_detected and have something like:

template <typename T, typename ...Ts>
using call_operator_type = decltype(std::declval<T>()(std::declval<Ts>()...));

template <typename T, typename ... Args>
using has_call_operator = is_detected<call_operator_type, T, Args...>;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM