从 char 数组到 std::string 的类型推导 [英] type deduction from char array to std::string
问题描述
我正在尝试使用可变参数模板编写 sum
函数.在代码中,我会写一些类似
I'm trying to write sum
function using variadic template.
In the code I would write something like
sum(1, 2., 3)
并且它将返回最通用的总和类型(在这种情况下 - double
).问题出在字符上.当我称之为
and it will return most general type of the sum (in this case - double
).
The problem is with characters. When I call it like
sum("Hello", " ", "World!")
模板参数被推导为例如const char [7]
,因此它不会编译.我找到了将最后一个参数指定为 std::string("World!")
的方法,但它并不漂亮,有没有办法实现对 std::string<的自动类型推导/code> 或正确重载
sum
?
template parameters are deduces as const char [7]
for example, thus it won't compile. I found the way to specify last argument as std::string("World!")
, but it's not pretty, is there any way to achieve automatic type deduction to std::string
or correctly overload sum
?
我到目前为止的代码:
template<typename T1, typename T2>
auto sum(const T1& t1, const T2& t2) {
return t1 + t2;
}
template<typename T1, typename... T2>
auto sum(const T1& t1, const T2&... t2) {
return t1 + sum(t2...);
}
int main(int argc, char** argv) {
auto s1 = sum(1, 2, 3);
std::cout << typeid(s1).name() << " " << s1 << std::endl;
auto s2 = sum(1, 2.0, 3);
std::cout << typeid(s2).name() << " " << s2 << std::endl;
auto s3 = sum("Hello", " ", std::string("World!"));
std::cout << typeid(s3).name() << " " << s3 << std::endl;
/* Won't compile! */
/*
auto s4 = sum("Hello", " ", "World!");
std::cout << typeid(s4).name() << " " << s4 << std::endl;
*/
return 0;
}
输出:
i 6
d 6
Ss Hello World!
推荐答案
我只想写一个简单的重载标识函数,专门处理 const char*
.
I would just write a simple overloaded identity function which handles const char*
specially.
template<typename T>
decltype(auto) fix(T&& val)
{
return std::forward<T>(val);
}
auto fix(char const* str)
{
return std::string(str);
}
template<typename T1, typename T2>
auto sum(const T1& t1, const T2& t2) {
return fix(t1) + t2;
}
template<typename T1, typename... T2>
auto sum(const T1& t1, const T2&... t2) {
return t1 + sum(t2...);
}
这篇关于从 char 数组到 std::string 的类型推导的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!