C++ Trait for Function Existence Is Not Working Wi

2019-08-18 08:15发布

问题:

I'm trying to solve this problem : how to evaluate if a class has a specific function with CRTP.

I got this as my class trait evaluation :

template <typename T>
class function_exists_trait
{
private:
    template <typename U>
    static auto test_todo(U * u) -> decltype(&U::exists) {}
    static auto test_todo(...) -> std::false_type {}

public:
    static constexpr bool value{ !std::is_same<decltype(test_todo(static_cast<T*>(nullptr))), std::false_type>::value };
};

And i tested it with some trivial classes :

struct t1 { void exists() {} };
struct t2 { void exists() {} };
struct t3 {};
struct t4 : public t1 {};
struct t5 : public t3 {};
struct t6 : public t3 { void exists() {} };

And I got the expected results. As expected, the evaluations give : 1 1 0 1 0 1 with this test : cout << function_exists_trait<t1>::value " " << ...

I got the expected results for the following CRTP simple implementations (0 1 1 1) :

template <typename t> struct u1 {};
struct crtp1 : public u1<crtp1> { void exists() {} };
template <typename t> struct u2 { void exists() {} };
struct crtp2 : public u2<crtp2> {};

cout << function_exists_trait<u1<int>>::value << " "
     << function_exists_trait<crtp1>::value << " "
     << function_exists_trait<u2<int>>::value << " "
     << function_exists_trait<crtp2>::value << endl;

The problem is this : when a try to evaluate the trait inside the CRTP base class, nothing is working and I do not understand why.

template <typename t> struct u3 { 
    static inline constexpr bool value{ function_exists_trait<t>::value }; 
};
struct crtp3 : public u3<crtp3> { void exists() {} };

template <typename t> struct u4 { 
    void exists() {}
    static inline constexpr bool value{ function_exists_trait<t>::value };
};
struct crtp4 : public u4<crtp4> {};

template <typename t> struct u5 {
    void exists() {}
    static inline constexpr bool value{ function_exists_trait<t>::value };
};
struct crtp5 : public u5<crtp5> {
    void exists() {}
};

The following code give this result : 0 0 - 0 0 - 0 0 - 0 0

cout << function_exists_trait<u3<int>>::value << " " << u3<int>::value << " - "
        << function_exists_trait<crtp3>::value << " " << crtp3::value << " - " 
        << function_exists_trait<crtp4>::value << " " << crtp4::value << " - "
        << function_exists_trait<crtp5>::value << " " << crtp5::value << endl;

Anybody have an explanation and/or a solution?

标签: c++ traits crtp