C 中的模板专业化中的字符串参数
string argument in template specialization in C++
在以下代码中,为什么必须在最后一行中的字符串" hello"之后以推断出参数的类型?这是对C 的字符串的明确铸造?
#include <iostream>
#include <string>
#include <vector>
using namespace std;
template <class T>
T addition(T const& a, T const& b){ return a + b;}
template <class T, size_t N>
T reduce(T const (&array)[N], T value = {}, T (*p)(T const&,T const&) = addition<T>)
{
T res = value;
for (int i = 0; i < N; i++) {
res = p(res,array[i]);
}
return res;
}
double multiply(double const& lhs, double const& rhs)
{
return lhs * rhs;
}
int main()
{
double pi[]{0.0505, 0.0505, 0.0405};
double factorial[]{1.0, 2.0, 3.0, 4.0, 5.0};
string concat[]{" ", "world"};
cout << reduce({1,2,3,4,5}) << endl;
cout << reduce(pi, 3.0) << endl;
cout << reduce(factorial, 1.0, multiply) << endl;
cout << reduce(concat, "hello"s) << endl;
}
"hello"s
中的 s
是字符串文字操作员。它返回std::string
,这意味着对reduce
的调用将与您作为第一个参数传递的std::string
数组匹配。
请注意,如果您没有写过using namespace std;
,则该示例将不起作用(这不是一个好主意(。
在C 14之前,您通常会编写std::string("hello")
。即使是如今,有些准则也更喜欢避免文字,因为您必须首先使用using namespace
访问它们,并且作为一个字符,它们可能很难注意到。
无需推断该参数,但是如果没有s
后缀,则无法匹配。
因为decltype("hello")
是const char(&)[6]
,这将使T=const char*
。但这与std::string(&)[2]
类型的第一个传递的参数concat
不匹配,该参数要求T
为std::string
。
s
后缀将字符串字面的字符串转换为std::string
。因此,是的,这是C 字符串的明确铸件,因为在C/C 字符串类型中不是语言的一部分,而是简单地作为数组实现。
相关文章:
- c++ 构造函数 将 1 个字符串参数转换为 3 个属性
- 对函数的 out 字符串参数使用 swap 与赋值
- sscanf() 有两个字符串参数
- isPalindrome不显示输出,isPalindrome函数未使用字符串输入作为字符串参数进行测试
- 如何通过C++在Python函数中传递字符串参数
- 将字符串参数传递给 ifstream
- Pybind11:将字符串*参数传递给构造函数
- 为什么我不能提供一个字符串参数来打印 ncurses?
- 为什么将char*传递给字符串参数会产生汇编错误
- 字符串参数常量字符* 和常量 wchar_t*
- 无法将字符串参数传递到构造函数中?
- 为什么对字符串参数的常量引用可以采用字符串文字?
- C 中的模板专业化中的字符串参数
- 如何使用单声道嵌入将字符串参数传递给 c# 方法
- 如何检查谷歌模拟中作为空指针传递的字符串参数
- 向 const 字符串参数发送 0 int 文本时的访问冲突
- 构造函数字符串参数未设置窗口标题
- C++ 重构采用 int 或字符串参数的方法
- 调用具有字符串参数direct vs variable的函数
- 如何使用 2 个字符串参数从 jni java 库调用