【问题标题】:Variadic template not compiled [duplicate]可变参数模板未编译[重复]
【发布时间】:2014-01-02 17:14:57
【问题描述】:

代码:

#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 &lt;&lt; "12345" &lt;&lt; std::endl;一样的结果模板函数有什么问题?

【问题讨论】:

  • 您在拆包语句中缺少.。将其更改为args...
  • 编辑问题,还有一条消息...
  • @AlexFarber 我很抱歉...

标签: c++ c++11 variadic-templates


【解决方案1】:

问题是您将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;
}

按预期工作。

【讨论】:

  • 你要找的词是“argument type-deduction”。
【解决方案2】:

有一个语法错误(缺少.)导致编译器发疯。

之后,您可能还会遇到out("12345", std::endl) 调用的问题,因为std::endl 是编译器无法选择的重写函数(只需将其转换为static_cast&lt;std::ostream&amp;(*)(std::ostream&amp;)&gt;(std::endl)

另外,out 中的递归以 out() 调用结束,但没有输出为 0 的参数。(另请参阅 yuri 回答:https://stackoverflow.com/a/20879525/924727

【讨论】:

  • 谢谢。 .. 是错字,已修复。从调用中删除 std::endl 并没有帮助,我猜是模板本身的问题。
  • 删除第一行template 后看起来更好。你是对的,std::endl 没有编译。但是你的选角不起作用:invalid static_cast from type ‘&lt;unresolved overloaded function type&gt;’ to type ‘std::ostream&amp;(std::ostream&amp;) {aka std::basic_ostream&lt;char&gt;&amp;(std::basic_ostream&lt;char&gt;&amp;)}
  • 糟糕:查看编辑(忘记了(*)
  • 谢谢。我又发了一个问题stackoverflow.com/questions/20879611/…把答案写在那里。
猜你喜欢
  • 1970-01-01
  • 2019-02-10
  • 2019-07-27
  • 2015-08-24
  • 1970-01-01
  • 1970-01-01
  • 2019-02-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多