为什么编译器抱怨f()不可见?
Why does compiler complain that f() is not visible?
#include <iostream>
using namespace std;
template <size_t N>
typename enable_if<(N > 1), void>::type f(){
cout << N - 1 << ' ';
f<N - 1>();
}
template <size_t N>
typename enable_if<N == 1, void> ::type f() {
cout << 1;
}
int main() {
f<4>();
}
编译器在第8行报错:
f< N - 1 >();
调用函数
f
,该函数在模板定义中既不可见,也无法在ADL
中找到。
将函数定义的顺序颠倒。
#include <iostream>
#include <type_traits>
using namespace std;
template <size_t N>
typename enable_if<N == 1, void> ::type f() {
cout << 1;
}
template <size_t N>
typename enable_if<(N > 1), void>::type f(){
cout << N - 1 << ' ';
f<N - 1>();
}
int main() {
f<4>();
}
输出:$ ./a.out
3 2 1 1
请注意,函数是在函数调用下面定义的。
有两种可能的方法:
方法1:
#include <iostream>
#include <type_traits>
using namespace std;
template <size_t N>
typename enable_if<N == 1, void> ::type f() {
cout << 1;
}
template <size_t N>
typename enable_if<(N > 1), void>::type f(){
cout << N - 1 << ' ';
f<N - 1>();
}
int main() {
f<4>();
}
方法2:
您可以前向声明 N==1
版本函数的原型
相关文章:
- 为什么所有C++编译器都会崩溃或挂起此代码
- 为什么C++编译器没有检测到正确声明的类?
- 为什么布尔开关语句有编译器警告?
- 为什么编译器将其解析为函数指针而不是递归调用?
- C++为什么我的编译器成功了,但我的计算机给出了调试错误?
- C++初学者:为什么我的编译器根据我的循环返回"name not found"?
- 为什么我的编译器无法弄清楚这种转换,它何时存在?
- 为什么编译器说"candidate template ignored: couldn't infer template argument 'InputIterator'"?
- 为什么编译器不检查被覆盖函数的存储类?
- 为什么编译器在使用"无常量复制构造函数"时抱怨?
- 为什么 std::count 比 MSVC 编译器的普通循环慢,但与 GCC 相等?
- 为什么 gcc 编译器标志未知?
- 当类型适当的构造函数可用时,为什么一个编译器尝试使用已删除的副本构造函数
- C 17 GCC编译器为什么会发出有关未定义的警告
- Clang 编译器为什么无法编译以下variadic模板代码
- 编译器为什么抱怨对齐
- 编译器为什么要将浮点数字的位数固定为6
- 编译器为什么要生成此程序集
- vtkCharts库既不适用于Visual Studio,也不适用于GCC编译器 - 为什么?
- 在c++中,当常量也可以工作时,编译器为什么选择非常量函数