小编Bap*_*tou的帖子

字符串文字左值和右值引用的函数重载

test对于左值空字符串,左值非空字符串和右值字符串,下面的函数已重载。我尝试使用Clang和GCC进行编译,但在两种情况下都没有达到我期望的结果。

#include <iostream>

void test(const char (&)[1]){ std::cout << __PRETTY_FUNCTION__ << std::endl; }

template <unsigned long int N>
void test(const char (&)[N]){ std::cout << __PRETTY_FUNCTION__ << std::endl; }

void test(char*&&){ std::cout << __PRETTY_FUNCTION__ << std::endl; }

int main(){
    char str1[] = "";
    char str2[] = "test";
    test("");
    test("test");
    test(str1);
    test(str2);
}
Run Code Online (Sandbox Code Playgroud)

使用clang 版本6.0.0-1ubuntu2的输出:

#include <iostream>

void test(const char (&)[1]){ std::cout << __PRETTY_FUNCTION__ << std::endl; }

template <unsigned long int N>
void test(const char (&)[N]){ std::cout << __PRETTY_FUNCTION__ << …
Run Code Online (Sandbox Code Playgroud)

c++ language-lawyer overload-resolution value-categories

16
推荐指数
1
解决办法
412
查看次数

JavaScript 字符串替换 vs replaceAll

ECMAScript 2021 添加了一个新的 String 函数replaceAll。很久以前,在一个不远的星系中,人们使用split+join或正则表达式来替换所有出现的字符串

我创建了以下示例来比较新方法和旧方法。虽然我可以在第一种情况下看到一些差异,例如我不能使用带有+ 的替换模式,或者我需要使用 来转义特殊字符,但在第二种情况下我看不出任何区别。splitjoinRegExp(str,"g")

新方法和旧方法有什么区别(行为差异、性能、浏览器兼容性...)?

const source = "abcdefabcdef";
const str1 = "abc", str2 = "xyz";
const reg1 = /abc/g, reg2 = "xyz";

//Case 1 : When we want to replace a string by another
console.log(source.split(str1).join(str2));
console.log(source.replace(new RegExp(str1,"g"),str2));
//versus
console.log(source.replaceAll(str1,str2));

//Case 2 : When we want to use a regular expression
console.log(source.replace(reg1,reg2));
//versus
console.log(source.replaceAll(reg1,reg2));

//Result = "xyzdefxyzdef"
Run Code Online (Sandbox Code Playgroud)

javascript string replaceall ecmascript-2021

8
推荐指数
1
解决办法
2304
查看次数

使用-声明现有名称空间类型与创建类型别名

这不是关于类型别名之间using以及typedef创建类型别名之间的区别的问题。我想提供从代码块或函数内部的名称空间访问现有类型的权限。

我发现了两种不同的方式:

我可以使用using声明“包含”类型:

using typename mynamespace::mytype;
Run Code Online (Sandbox Code Playgroud)

或者我可以创建一个类型别名:

typedef mynamespace::mytype mytype;
using mytype = mynamespace::mytype; //C++11
Run Code Online (Sandbox Code Playgroud)
  1. 有什么区别吗?
  2. 每种语法的优缺点是什么?
  3. 哪个是最常用/推荐的?

谢谢。

相关问题:使用基类中的现有类型声明与在子类中创建类型别名

c++ typedef using-declaration type-alias

5
推荐指数
1
解决办法
80
查看次数

iostream运算符重载的C ++异常规范

未指定对ostream运算符<<的调用是否会失败或引发任何异常,而我从未遇到过。

  1. 是否存在ostream operator <<可能失败的情况?
  2. 如果否,为什么标准不对这些重载不加任何其他说明?
  3. 以下重载有效吗?好的做法?常用的?
  4. istream运算符有相同问题>>
struct MyClass {
    int data;
    // I/O operators with noexcept specifier
    friend std::istream& operator>>(std::istream &in, MyClass &obj) noexcept;
    friend std::ostream& operator<<(std::ostream &out, const MyClass &obj) noexcept;
};
Run Code Online (Sandbox Code Playgroud)

c++ iostream operator-overloading noexcept

2
推荐指数
1
解决办法
37
查看次数