在可变模板函数中串联字符串(和数字) [英] Concatenating strings (and numbers) in variadic template function
本文介绍了在可变模板函数中串联字符串(和数字)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图写一个函数,它接受各种字符串或数字(使用 std :: to_string
并连接它们。
I am attempting to write a function that takes a variety of strings or numbers (that work with std::to_string
and concatenate them. I've got it working with just strings, but I am having trouble with specializing depending on input as string or number.
我的代码是这样调用的:
My code is called like this:
stringer(hello,world,2,15,0.2014,goodbye,world)
这里是我有:
inline std::string stringer(const std::string &string)
{
return string;
}
template <typename T, typename... Args>
inline std::string stringer(const std::string &string, T &&val, Args &&...args)
{
return stringer(string+std::to_string(val), std::forward<Args>(args)...);
}
template <typename... Args>
inline std::string stringer(const std::string &string, Args &&...args)
{
return stringer(string, std::forward<Args>(args)...);
}
目前它正在打破任何多个字符串,除非以下都是数字(由于to_string)。我如何专业化基于字符串或数字使上述工作?谢谢。
Currently it is breaking on any more than one string added unless the following are all numbers (due to the to_string). How can I specialize based on string or number to make the above work? Thanks.
推荐答案
inline std::string const& to_string(std::string const& s) { return s; }
template<typename... Args>
std::string stringer(Args const&... args)
{
std::string result;
using ::to_string;
using std::to_string;
int unpack[]{0, (result += to_string(args), 0)...};
static_cast<void>(unpack);
return result;
}
这篇关于在可变模板函数中串联字符串(和数字)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文