enable_if不能用于禁用此声明

Mat*_*nti 6 c++ templates sfinae

我显然没有足够的SFINAE经验来处理这个问题.实际上我的印象是它一直工作到现在,这种问题开始出现在过去的半小时内,在我的代码中到处都是.

#include <iostream>

using namespace std;

template <unsigned int N, typename = typename enable_if <N >= 100> :: type> 
struct more_than_99
{
};

int main()
{
    more_than_99 <0> c;
}
Run Code Online (Sandbox Code Playgroud)

它说

No type named 'type' in 'std::__1::enable_if<false, void>'; 'enable_if' cannot be used to disable this declaration
Run Code Online (Sandbox Code Playgroud)

在与模板声明对应的行上.到底是怎么回事?我一直使用这种语法来启用和禁用我的模板类,它总是在实例化的行上抛出错误,而不是在声明的行上.

你能不能迂腐地解释我在这里做错了什么?

App*_*les 4

关于为什么错误发生在模板定义而不是实例化时,其他答案是正确的。

当尝试实例化“more_than_99 <0> x;”之类的东西时,我需要抛出一个错误 在我尝试实例化它的行上。比如“嘿,这种类型不存在”。

像这样的事情怎么样?

template <unsigned int N, bool B = (N>=100)>
struct more_than_99;

template <unsigned int N>
struct more_than_99<N,true>
{};

int main()
{
    more_than_99 <0> c; // error: implicit instantiation of undefined template 'more_than_99<0, false>'
}
Run Code Online (Sandbox Code Playgroud)

为了使其更加健壮,并尝试防止意外实例化more_than_99<0,true>,这也有效(C++11):

template <unsigned int N, bool B>
struct _impl_more_than_99;

template <unsigned int N>
struct _impl_more_than_99<N,true>
{};

template <unsigned int N>
using more_than_99 = _impl_more_than_99<N, (N>=100)>;

int main()
{
    more_than_99 <0> c; // error: implicit instantiation of undefined template '_impl_more_than_99<0, false>'
}
Run Code Online (Sandbox Code Playgroud)

尽管错误消息引用了_impl_类型。

您可以将 隐藏_impl_在详细名称空间或其他内容中,然后只记录more_than_99别名,就好像它是实际类型一样。

但是,您将无法阻止_impl_more_than_99<0,true>.