测试是否存在非类成员函数(SFINAE)

时间:2016-08-02 09:59:49

标签: c++ templates c++11 template-meta-programming 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来检测是否存在类成员方法。但对于我的问题,我无法找到解决方案......任何人?

谢谢, 本

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

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)) {
};

1 个答案:

答案 0 :(得分:1)

您可以使用以下内容:

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等于trueclass A定义print函数,否则等于false

相关问题