【问题标题】:SFINAE member function existence test issueSFINAE成员函数存在测试问题
【发布时间】:2012-06-30 09:55:53
【问题描述】:

我有这个成员函数测试:

template <typename T> 
struct has_member {
    template <typename U>  static true_type  f(decltype(declval<U>().member()) *);
    template <typename>    static false_type f(...);
    static const bool value =  decltype(f<T>(0))::value;
};

当存在具有给定名称的成员函数时,如果该函数具有不带参数的重载,则它的计算结果为 true。对于此类函数以及 STL 容器,它可以正常工作,但元素访问函数(前、后等)除外,在这些函数中,它总是计算为 false。

这是为什么呢?我有 mingw g++ 4.7。

【问题讨论】:

  • 更改为尾随返回类型有帮助吗? auto f(U* p)-&gt; decltype(p-&gt;member(), true_type());

标签: c++ sfinae


【解决方案1】:

那是因为这些函数返回引用,而你声明了一个指向返回值的指针,即指向引用的指针,这是不可能的。

快速解决方法是:

template <typename U>  static true_type  
        f(typename remove_reference< decltype(declval<U>().member()) >::type *);

PS:如果您在 SFINAE 失败时强制编译器给出错误并且您认为它不应该出现错误,则此类错误可以(相对)容易解决。

我的意思是,在您的代码中,只需注释掉 false_type 并在 true_type 是唯一选项时查看编译器的错误。在一堆毫无意义的台词之间有以下内容:

test.cpp:9:50: error: forming pointer to reference type
    ‘__gnu_cxx::__alloc_traits<std::allocator<int> >::value_type& {aka int&}’

【讨论】:

  • 谢谢,成功了。我想我也想出了一种不删除引用的方法:我将“ typename Check = decltype(declval().front() ”作为第二个模板参数,并让 f 传递一个 char 指针。
  • @AndrásKovács - 这样更好。
猜你喜欢
  • 2011-03-23
  • 1970-01-01
  • 1970-01-01
  • 2016-06-26
  • 1970-01-01
  • 1970-01-01
  • 2013-09-05
  • 1970-01-01
  • 2020-08-04
相关资源
最近更新 更多