C 中的模板专业化中的字符串参数

string argument in template specialization in C++

本文关键字:字符串 参数 专业化      更新时间:2023-10-16

在以下代码中,为什么必须在最后一行中的字符串" 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不匹配,该参数要求Tstd::string

s后缀将字符串字面的字符串转换为std::string。因此,是的,这是C 字符串的明确铸件,因为在C/C 字符串类型中不是语言的一部分,而是简单地作为数组实现。