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

时间:2019-05-26 15:42:09

标签: c++

在下面的代码中,为什么要推断出参数的类型,最后一行中的字符串“ hello”之后的“ s”是必需的?是在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;
}

2 个答案:

答案 0 :(得分:3)

s中的"hello"sstring literal operator。它返回一个std::string,这意味着对reduce的调用将与您作为第一个参数传递的std::string数组匹配。

请注意,如果您未编写using namespace std;,则该示例将不起作用(这并不是一个好主意)。

在C ++ 14之前,您通常会改写std::string("hello")。即使在当今,一些准则也更倾向于避免使用文字,因为您必须首先使用using namespace来访问它们,并且作为一个字符,可能很难注意到它们。

答案 1 :(得分:0)

没有必要推论该参数,但是如果没有后缀s,它将不匹配。

因为decltype("hello")const char(&)[6],那将构成T=const char*。但这与类型为concat的第一个传递参数std::string(&)[2]不匹配,后者要求Tstd::string

后缀s将字符串文字转换为std::string。因此,是的,它是对c ++字符串的显式转换,因为在C / C ++字符串类型中,该类型不是该语言的一部分,而是将其简单地实现为数组。