【问题标题】:Test if a not class member function exists (SFINAE) [duplicate]测试是否存在非类成员函数(SFINAE)[重复]
【发布时间】:2016-08-02 09:59:48
【问题描述】:

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

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

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

我的问题是: 有没有办法让类型 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)) {
};

【问题讨论】:

  • 模板 你的意思是 T?
  • 你有一个typename Ratio 但使用T... 它们是同一个参数吗?你试过什么吗?
  • 你说它存在是什么意思?就目前而言(前提是您更正了模板参数名称拼写错误),它将为您想要使用的任何类型自动生成,因为它没有 SFINAE 约束。
  • 你对方法使用了什么解决方案?
  • T 是为其定义了 print 的对象之一的类型。比率在函数内部使用。

标签: c++ templates c++11 template-meta-programming sfinae


【解决方案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&lt;A&gt;::value 等于 true,对于 class A,定义了 print 函数,否则等于 false

【讨论】:

  • 非常感谢,您的解决方案似乎有效。
猜你喜欢
  • 2011-03-23
  • 1970-01-01
  • 2013-09-05
  • 1970-01-01
  • 2016-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多