我正在尝试解决此问题:如何使用CRTP评估类是否具有特定功能。
这是我的班级特质评估:
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 };
};
我用一些简单的类对其进行了测试:
struct t1 { void exists() {} };
struct t2 { void exists() {} };
struct t3 {};
struct t4 : public t1 {};
struct t5 : public t3 {};
struct t6 : public t3 { void exists() {} };
我得到了预期的结果。如预期的那样,此测试的评估结果为:1 1 0 1 0 1 1:cout << function_exists_trait<t1>::value " " << ...
对于以下CRTP简单实现(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;
问题是这样的:当尝试评估CRTP基类内部的特征时,什么都没有起作用,我也不明白为什么。
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() {}
};
以下代码给出了此结果: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;
有人有解释和/或解决方案吗?