C++20:如何检查类是否含指定名称参数、任意返回值的方法?
C++20检查类是否存在指定成员方法的实现方案
优先方案:使用C++20 Concepts
要检查Token类是否存在任意返回类型的get_executor()方法,可通过requires表达式编写对应的concept:
class Token; template <typename T> concept has_method_get_executor = requires(T t) { { t.get_executor() }; // 仅验证调用合法性,不限制返回类型 }; // 编译期分支使用示例 if constexpr (has_method_get_executor<Token>) { // Token类存在get_executor()方法时执行的逻辑 } else { // Token类不存在该方法时执行的逻辑 }
注意:if constexpr中直接使用has_method_get_executor<Token>即可,无需加括号——concept本质是编译期布尔常量。这个实现会在编译期验证:给定类型T的对象能否调用get_executor(),无论返回值是什么类型,只要调用合法就满足concept。
替代方案:SFINAE(不使用Concepts)
如果场景限制无法使用C++20 Concepts,可借助SFINAE和std::void_t实现同样的编译期检查:
#include <type_traits> class Token; // 基础模板,默认判定为不存在目标方法 template <typename T, typename = void> struct has_method_get_executor : std::false_type {}; // 特化模板:当T可调用get_executor()时,匹配此模板并判定为存在 template <typename T> struct has_method_get_executor<T, std::void_t<decltype(std::declval<T>().get_executor())>> : std::true_type {}; // 辅助变量模板,简化调用 template <typename T> inline constexpr bool has_method_get_executor_v = has_method_get_executor<T>::value; // 编译期分支使用示例 if constexpr (has_method_get_executor_v<Token>) { // 存在目标方法时的逻辑 } else { // 不存在目标方法时的逻辑 }
该方案通过std::void_t的特性触发SFINAE:当decltype(std::declval<T>().get_executor())合法时,特化模板会被优先匹配,此时value为true;否则使用基础模板的false。
内容的提问来源于stack exchange,提问作者mouse_00
相关产品推荐
相关产品推荐

