可变参数模板未编译
Variadic template not compiled
代码:
#include <iostream>
template<typename T>
void out() // line 4
{
}
template<typename T, typename... Args>
void out(T value, Args... args) // line 9
{
std::cout << value;
out(args...); // line 12
}
int main()
{
out("12345", std::endl); // line 17
return 0;
}
构建错误:
g++ -O0 -g3 -Wall -c -fmessage-length=0 -std=c++11 -pthread -MMD -MP -MF"main.d" -MT"main.d" -o "main.o" "../main.cpp"
../main.cpp: In function ‘int main()’:
../main.cpp:17:24: error: no matching function for call to ‘out(const char [6], <unresolved overloaded function type>)’
../main.cpp:17:24: note: candidates are:
../main.cpp:4:6: note: template<class T> void out()
../main.cpp:4:6: note: template argument deduction/substitution failed:
../main.cpp:17:24: note: candidate expects 0 arguments, 2 provided
../main.cpp:9:6: note: void out(T, Args ...) [with T = const char*; Args = {}]
../main.cpp:9:6: note: candidate expects 1 argument, 2 provided
我希望这个程序给出与std::cout << "12345" << std::endl;
模板函数中有什么问题相同的结果?
问题是你把你的无参数版本out
是一个模板,如果不显式提供模板参数,就不能调用它。因此
void out() {}
template<typename T, typename... Args>
void out(T value, Args... args) {
std::cout << value;
out(args...);
}
int main() {
out(1, 2.0, "3");
return 0;
}
按预期工作。
有一个语法错误(错过.
),使编译器发疯。
之后,您可能还会遇到out("12345", std::endl)
调用的问题,std::endl
编译器无法选择的覆盖函数(只需将其转换为static_cast<std::ostream&(*)(std::ostream&)>(std::endl)
此外,out
中的递归以 out()
调用结束,但没有 out 的 0 参数。(另见尤里回答:https://stackoverflow.com/a/20879525/924727)
相关文章:
- std::具有相同基类的类的变体
- 二叉排序树无法编译
- 编译时未启用intel oneApi CUDA支持
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 编译包含字符串的代码时遇到问题
- 尝试更改 main 函数内的全局变量值时出现编译错误 C++.
- std::结构复杂,使编译速度变慢
- C 如何在编译时检查变体映射的类型
- 为原始指针、智能指针和值创建成员函数的编译时变体
- Unix 宏在使用 -std=c++0x 标志编译时变得未定义
- 在编译时从变体中获取类型
- 使用访问者中的Boost变体中的类型不编译
- BOOST_SPIRIT_DEBUG_NODE无法在变体节点上编译
- Boost变体apply_viewer编译错误
- 注释函数的内容,但保持对函数的调用不变.编译器是否弄清楚不编译函数
- 我编译的C++程序太小.我怎样才能把它变大
- 如何在编译时通过模板形参默认值的名称/指针获取函数的类型
- 哪种方法更适合为函数提供编译时间常数?函数实参与模板形参
- c++ 03:是否有一种方法可以使一个类型每次被包含在模板形参中时都会编译成不同的类型?
- 内联函数是否使对编译后的二进制文件进行逆向工程变得更加困难?