c++ - enable_if 不能用于禁用此声明

标签 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;
}

它说

No type named 'type' in 'std::__1::enable_if<false, void>'; 'enable_if' cannot be used to disable this declaration

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

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

最佳答案

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

I need an error to be thrown when trying to instantiate something like `more_than_99 <0> x;' on the line where I try to instantiate it. Something like "hey, this type doesn't exist".

这样的事情怎么样?

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>'
}

为了让它更健壮一点,并试图防止意外实例化 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>'
}

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

你可以隐藏 _impl_在详细 namespace 或其他内容中,并记录 more_than_99别名就好像它是实际类型一样。

但是,您将无法阻止_impl_more_than_99<0,true> 的恶意实例化。 .

关于c++ - enable_if 不能用于禁用此声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30380787/

相关文章:

c++ - 是否有可直接嵌入 C/C++ 程序的 C/C++ 编译器/链接器?

C++ 通用节点类不会采用不同类型的节点

c++ - C++ 模板中的非法间接寻址

c++ - 检查两种类型是否属于同一模板

c++ - 具有 SFINAE 虚拟参数的模棱两可的模板

c++ - 如何在 C++ 中使用宏生成任意长的参数列表?

javascript - 如何使用 Swig 将 JavaScript 中的关联数组映射到 C++ 中的字符串映射?

带复制和赋值的 C++ Qt 反射

c++ - 派生模板类访问基类成员数据

c++ - 检查模板参数是否有成员函数