在編譯期獲得常量 bool,指示類型 A 和 B 的實例能否用 == 比較。用於委託 (delegate) 等場景:有 == 則用它比較,否則退化為地址比較或直接 true。
利用 decltype 和 std::declval 構造表達式,配合 std::void_t (C++17) 或 std::enable_if 進行特徵檢測。
#include <type_traits> #include <utility> templatestruct has_equal_operator : std::false_type {}; template struct has_equal_operator () == std::declval())>> : std::true_type {}; // 使用 static_assert(has_equal_operator ::value); static_assert(!has_equal_operator ::value);
templatestruct has_equal_operator : std::false_type {}; template struct has_equal_operator () == std::declval()), void>::value >::type> : std::true_type {}; // 注意:需處理 decltype 非 void 情況,實際更複雜
原文給出的代碼較繁雜,核心是利用 decltype(expr) 在模板參數中觸發 SFINAE。
templatebool equal(const T& a, const T& b) { if constexpr (has_equal_operator ::value) // C++17 if constexpr return a == b; else return &a == &b; // 地址比較 fallback }
concept EqualityComparable = requires(T a, U b) { a == b; };。