Stroustrup C++ 第 4 版 Ed 第 796 页指出
"If
Enable_if
’s condition evaluates tofalse
, the whole function declaration of which it is part is completely ignored." and "...we don’t declare anything.".
我还读过this suggested thread其中 SFINAE 仅当模板参数的参数推导中的替换导致构造不正确时才起作用。
对于这个例子,我试图理解 SFINAE 如何省略 Enable_if<false, T> f0(int x) {};
构造。
是不是因为缺少返回类型::type
使模板构造语言形式错误?
#include <type_traits>
using namespace std;
template<bool B, typename T>
using Enable_if = typename std::enable_if<B, T>::type;
struct X
{
template <class T>
Enable_if<false, T> f0(int x) {};
template <class T>
Enable_if<true, T> f0(int x) {};
};
int main(void)
{
X xx;
xx.f0<void>(0);
return 0;
}
我理解前面提到的构造线程中的情况:
template <typename enable_if<false>::type* = nullptr>
void f0() {}
这是因为模板参数格式不正确(没有 ::type
来分配 nullptr
。)
最佳答案
I'm trying to understand how SFINAE omits the
Enable_if<false, T> f0(int x) {};
construct. Is it because of the lack of a return type::type
makes the template construct ill-formed language-wise?
简短回答:不!
您需要看看 SFNINAE 基本上是如何工作的 a good c++ book 。例如来自cppreference.com
This rule applies during overload resolution of function templates: When substituting the explicitly specified or deduced type for the template parameter fails, the specialization is discarded from the overload set instead of causing a compile error.
意思是,您首先需要重载模板函数!这已在给定的示例代码中实现。
其次, std::enable_if
部分。它检查您在中提供的条件
template< bool B, class T = void >
// ^^^^^^^ -----------------------> here!!
struct enable_if;
在编译时,决定是否 to activate the part below or not .
The standard library component
std::enable_if
allows for creating a substitution failure in order to enable or disable particular overloads based on a condition evaluated at compile time.
在您的代码中,对于给定的重载
template <class T>
Enable_if<false, T> f0(int x) {};
// ^^^^^ ---------------> CONDITION == false
条件是false
,因此实际上,在编译器完成编译后,这部分(代码)将不存在。
Is it because of the lack of a return type
::type
makes the template construct ill-formed language-wise?
由于上述原因,否;不是这个原因!
通过提供这样的模板类型别名
template<bool B, typename T>
using Enable_if = typename std::enable_if<B,T>::type;
// ^^^^^^^ --> type has been mentioned here!
您提到了::type
通过别名类型 Enable_if</*condition*/, T>
.
关于c++ - std::enable_if 如何阻止成员模板的声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63095464/