【发布时间】:2017-03-26 15:52:01
【问题描述】:
这是我的代码:
#include <iostream>
#include "Generator.h" // user-defined class
char getChar(Generator & generator)
{
return generator.generateChar();
}
char getChar(int pos, const string & s)
{
return s[pos];
}
template<typename... StringType>
void func(Generator & generator, StringType &&... str)
{
char ch;
int size = sizeof...(StringType);
// lots of things to do
if (size == 0)
{
ch = getChar(generator);
}
else
{
ch = getChar(1, std::forward<StringType>(str)...); // ERROR here
}
}
int main(int argc, char ** argv)
{
Generator generator;
func(generator);
func(generator, "abc");
return 0;
}
一开始我只是重载了函数func,发现有很多类似的代码。所以我正在考虑使用可变参数模板来获得更好的设计。 (How to make a better design if two overload functions are similar)
但是不知道为什么会报错:
main.cpp:27:8: 错误:没有匹配的函数调用“getChar” ch = getChar(1, std::forward(str)...);
main.cpp:37:2:注意:在此处请求的函数模板特化“func”的实例化
函数(生成器);main.cpp:6:6: 注意:候选函数不可行:第一个参数 char 没有从“int”到“Generator &”的已知转换
getChar(生成器和生成器)main.cpp:11:6:注意:候选函数不可行:需要 2 个参数,但提供了 1 个 char getChar(int pos, const string & s)
顺便说一句,我可以设计一些避免使用 if...else... 与 sizeof...(StringType) 一起使用的设计吗?
【问题讨论】:
标签: c++ c++11 templates variadic-templates