测试是否存在 not class 成员函数 (SFINAE)

Test if a not class member function exists (SFINAE)

我定义了很多对象,我为其中的一些对象定义了一个函数:

template <typename Ratio> 
auto print(const T &t, bool a= true, bool b= true)
{
    std::stringstream ss;
    // ... do stuff ...
    return ss.str();
}

其中 T 是为其定义打印的对象之一的类型。比率在函数内部使用。

我的问题是: 有没有办法让类型 T 找到这个函数是否存在?

对于其他用途,我已经使用模板和 SFINAE 来检测 class 成员方法是否存在。但是对于我这里的问题,我找不到解决方案...有人吗?

谢谢, 本

PS:我的代码中使用 SFINAE 的示例,我需要在其中检测 class 成员方法是否存在。

static T none() { ... }

/**
 * SFINAE for checking id none method exists
 */
template <class T>
static auto hasNoneMethod(int)
    -> std::integral_constant<bool, std::is_same<T, decltype(T::none())>::value>;
template <class>
static auto hasNoneMethod(...) -> std::false_type;

/**
 * Type-Function
 */
template <typename T>
struct HasNoneMethod: decltype(detail::hasNoneMethod<T>(0)) {
};

你可以这样使用:

template <class T>
static auto hasPrintMethod(int)
->std::integral_constant<bool, std::is_class<decltype(print(T()))>::value>;

template <class>
static auto hasPrintMethod(...)->std::false_type;

template <typename T>
struct HasPrintMethod : decltype(hasPrintMethod<T>(0)) {
};

这里的 decltype(print(T())) 对于 类 是 std::string,您的非成员函数是为其定义的,对于其他 类 是错误的类型。因此,根据 SFINAE 概念,HasPrintMethod<A>::value 等于 true 对于 class A 定义了 print 函数,否则等于 false