在这种情况下,enable_if如何工作

时间:2017-10-16 19:18:59

标签: c++ metaprogramming

#include <iostream>
#include <functional>
#include <memory>

using namespace std;

template<typename T = int> std::enable_if_t<!std::is_arithmetic<T>{}, T> nope() {}

int main() {
    nope();
}

这是一个无法编译的简单代码。如果改变了这个:

int main() {
        nope();
}

int main() {
        nope<std::string>();
}

它开始编译。 问题是为什么它的工作方式有效?更具体地说,为什么编译器会告诉我:

  

没有用于调用&#39; nope()&#39;

的匹配功能

而不是

  找不到

enable_if :: type   (如果不满足条件,它确实不存在,这是真的吗?)

谢谢。

1 个答案:

答案 0 :(得分:0)

如果您致电nope(),则template类型默认为intstd::enable_if_t<!std::is_arithmetic<T>{}, T>false返回!std::is_arithmetic<int>{}并失败。

nope<int>()的调用也会失败,原因与nope()失败的原因相同。

另一方面,nope<std::string>true中获得is_arithmetic并返回工作函数。

使用clang++版本5.0触发的编译器错误非常清楚地解释了结果:

  

候选模板已被忽略:要求&#39; !std::is_arithmetic<int>{}&#39;不满意[with T = int] std::enable_if_t<!std::is_arithmetic<T>{}, T> nope() {}

相关问题