【发布时间】:2020-01-09 20:46:54
【问题描述】:
我是可变参数模板函数的新手。我写了一个简单的类StringStream,它有一个可变参数模板函数,它从可变模板参数(字符串、整数等)创建一个std::string。
#include <string>
#include <sstream>
class StringStream
{
public:
StringStream() = default;
~StringStream() = default;
template<typename T>
std::string Stringify(const T &value)
{
mStream << value;
return mStream.str();
}
template<typename T, typename... Ts>
std::string Stringify(const T& value, Ts... values)
{
mStream << value;
return Stringify(values...);
}
private:
std::stringstream mStream;
};
我现在要做的是在StringStream 中使用std::string 成员而不是std::stringstream,并根据Stringify() 的参数构建字符串。对于不是std::string 的参数,我想用std::to_string() 转换为字符串,否则我只是连接参数。我遇到了编译器错误。这是我修改后的课程:
class StringStream
{
public:
StringStream() = default;
~StringStream() = default;
template<typename T>
std::string Stringify(const T &value)
{
mString += std::to_string(value);
return mString;
}
template<>
std::string Stringify<std::string>(const std::string& value)
{
mString += value;
}
template<typename... Ts>
std::string Stringify(const std::string& value, Ts... values)
{
mString += value;
return Stringify(values...);
}
template<typename T, typename... Ts>
std::string Stringify(const T& value, Ts... values)
{
mString += std::to_string(value);
return Stringify(values...);
}
private:
std::string mString;
};
我的编译器错误提示:
error C2665: 'std::to_string': 9 个重载都不能转换所有参数类型
我这样调用函数:
int main()
{
int age;
std::cin >> age;
StringStream ss;
std::cout << ss.Stringify("I", " am ", age, " years ", "old") << std::endl;
}
有没有办法解决这个问题?
【问题讨论】:
-
用双引号写的内容是
const char*,而不是std::string。您需要单独处理。
标签: c++ c++11 variadic-templates variadic-functions template-argument-deduction