为什么具有真正价值enable_if似乎与直接放置空白的工作方式不同
Why does enable_if with true value seem to work differently than putting void in directly?
当我尝试使用部分专用化实例化我的模板化函子时,我遇到了歧义错误。 下面的Foo和Bar是相同的,只是Foo
的enable_if_t
被替换为Bar
中的void
。
#include <iostream>
#include <vector>
using namespace std;
template<class T, class Enable = void>
struct Foo;
template<class T>
struct Foo<T, enable_if_t<!std::is_pointer<T>::value>>{
void operator()(){
}
};
template<class T, class...Rest>
struct Foo<std::vector<T, Rest...>>
{
void operator()(){
cout<<"In vector"<<endl;
}
};
template<class T, class Enable = void>
struct Bar;
template<class T>
struct Bar<T, void>{
void operator()(){
}
};
template<class T, class...Rest>
struct Bar<std::vector<T, Rest...>>
{
void operator()(){
cout<<"In vector"<<endl;
}
};
int main()
{
// Foo<vector<int>> f; // <== this fails with the error below:
Bar<vector<int>> b;
}
如果注释掉的行被带回,我会得到以下内容
prog.cc:46:22: error: ambiguous partial specializations of 'Foo<std::__1::vector<int, std::__1::allocator<int> >, void>'
Foo<vector<int>> f;
^
prog.cc:10:8: note: partial specialization matches [with T = std::__1::vector<int, std::__1::allocator<int> >]
struct Foo<T, enable_if_t<!std::is_pointer<T>::value>>{
^
prog.cc:17:8: note: partial specialization matches [with T = int, Rest = <std::__1::allocator<int>>]
struct Foo<std::vector<T, Rest...>>
有人可以解释一下发生了什么吗? 我以为enable_if_t<SOME_TRUE_VALUE>
的类型是void
,所以我不明白为什么他们的行为不同。
此外,如果有人可以提供资源来"简单"描述用于在可行的部分专业化(即不是规范)之间进行选择的过程,那就太棒了。
n.m. 从评论中得到的回答:
你的两个专业都不比另一个专业更专业。因此,当两者匹配时,存在歧义。OTOH 当你使用 void 时,第二个专业化与任何东西都匹配,因此第一个专业化变得严格地更加专业化。
相关文章:
- 如何以优化的方式同时迭代两个间距不相等的数组
- 为什么我可以将变量存储在不是其最小对齐方式的倍数的地址?
- 而不是那么多的 if 语句,我想要一个逻辑,我可以用一个语句或优化的方式来完成
- Gtkmm 窗口为空白,不显示任何小部件或标题
- 如果第一个元素包含任何零,则我的程序以不希望的方式运行
- 如何使用打印到 PDF 打印机在 MFC 和 CView 中以编程方式打印而不提示输入文件名?
- C++结构模板变量快捷方式定义不起作用
- C++|以一种很好的方式将树(不一定是二进制的)打印到stdout
- 为什么智能指针不能用通常的指针方式声明
- 日食快捷方式不起作用
- 如何跳过空白但不跳过换行符
- 编辑控件的行为方式不该如此
- 打印所有空白(实际上不打印任何标记)
- 空白或不执行任何操作的三元运算符的第二个或第三个参数
- 运算符 [] 和 insert() 函数在 C++ 映射中的行为方式不应该相同吗?
- QTextEdit focusOut 以编程方式不起作用
- cocos2d- x3创建标签的方式不被弃用
- 如何编译我的c++库在纯Android Studio的方式(不指定任何.mk文件在我们自己)
- 什么会导致死亡<<变量& lt; & lt;“ t";当输出超过终端宽度时,打印空白而不是值
- 我可以以某种方式不写出完整的限定返回类型名称吗?