【问题标题】:In continuation of my attempts to understand std::enable_if usage继续我试图理解 std::enable_if 用法
【发布时间】:2018-04-09 06:41:00
【问题描述】:

在这段代码中:

#include <iostream>
#include <cstdlib>
#include <type_traits>
#include <ios>

using std::enable_if;
using std::is_same;
using std::boolalpha;
using std::cout;
using std::endl;

template <typename T>
struct S {
  S(): t(static_cast<T>(NULL)) { }

  // void type() {
  //   cout << boolalpha;
  //   cout << is_same<T,int>::value << endl;
  // }

  template <typename enable_if<is_same<T,int>::value,T>::type>
  void type() {
    cout << boolalpha << true << endl;
  }

  T t;
};

int main(){
  S<int> s;
  s.type();
  return(0);
}

我成功编译并输出了作为非模板函数实现的方法type();但是,对于使用 std::enable_if 实现为模板函数的相同方法,我收到以下编译错误:

so_main.cpp:23:11: error: no matching member function for call to 'type'
        s.type();
        ~~^~~~
so_main.cpp:15:73: note: candidate template ignored: couldn't infer template argument ''
        template<typename enable_if<is_same<T,int>::value,T>::type>void type(){cout << boolalpha << true << endl;}
                                                                        ^
1 error generated.

我的理解是这两种情况下实现的逻辑是相似的。 当方法是非模板时,T 的类型被证实为int。但是,当std::enable_if用于启用相同条件的模板功能(即Tint)时,代码无法编译。

【问题讨论】:

  • 为什么这个问题被否决了?因为一开始的租金?否则,这是一个完全有效且措辞恰当的问题;很多人对 SFINAE 的这种特殊性有疑问。
  • @@SU3 不幸和可悲的是,本论坛某些成员的行为存在很多任意行为,正如这篇帖子的否决票所证明的那样,没有任何解释

标签: c++14 sfinae


【解决方案1】:

这是因为 SFINAE 仅适用于与模板本身相关的模板参数。 立即上下文的标准调用。在您的代码示例中,T 是类模板的模板参数,而不是成员函数模板的模板参数。

您可以通过为您的函数提供一个默认为 T 的虚拟模板参数并在其上使用 SFINAE 来规避此问题,如下所示:

template <typename U=T>
typename enable_if<is_same<U,int>::value>::type type() {
  cout << boolalpha << true << endl;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-05
    • 2022-06-15
    • 1970-01-01
    • 2014-08-29
    • 2017-07-20
    • 2018-07-05
    • 2012-10-26
    相关资源
    最近更新 更多