gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:34:12 24 4
gpt4 key购买 nike

我显然没有足够的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com