【发布时间】:2012-06-07 17:47:59
【问题描述】:
所以我一直在探索folly- Facebook 的开源库,他们的大多数实用函数都使用 cstrings 而不是字符串。他们为什么这样做呢?这些示例传入对 std::string 的引用,并将其隐式转换为 cstring。这是他们的一个示例函数,我希望这个问题能够重点关注:
函数的调用方式:
// Multiple arguments are okay, too. Just put the pointer to string at the end.
toAppend(" is ", 2, " point ", 5, &str);
Conv.h 内部
/**
* Everything implicitly convertible to const char* gets appended.
*/
template <class Tgt, class Src>
typename std::enable_if<
std::is_convertible<Src, const char*>::value
&& detail::IsSomeString<Tgt>::value>::type
toAppend(Src value, Tgt * result) {
// Treat null pointers like an empty string, as in:
// operator<<(std::ostream&, const char*).
const char* c = value;
if (c) {
result->append(value);
}
}
什么时候函数应该使用 cstrings 而不是字符串?为什么他们不编写函数来通过引用获取 std::string,因此可以像这样调用函数:
toAppend(" is ", 2, " point ", 5, str);
我唯一的猜测是为了提高效率,但是将 std::string 转换为 cstring 是否比传递 std::string 的引用更有效?也许对 cstring 的实际操作比调用 std::string 成员函数更快?或者,如果他们只有一个 cstring 开头,也许他们可以调用该函数?嗯
【问题讨论】:
-
它接受 std::string* 而不是 std::string& 正如你所建议的。它不接受 const char*。在内部 std::string* std::string & 是相同的。参考文献通常是首选,但他们可能已经做到了一致性。
标签: c++ string function c++11 parameter-passing