相关疑难解决方法(0)

如何为我的班级提供交换功能?

启用swapSTL算法的正确方法是什么?

1)会员swap.是否std::swap使用SFINAE技巧来使用该成员swap.

2)自由站立swap在同一名称空间中.

3)部分专业化std::swap.

4)以上所有.

谢谢.

编辑:看起来我没有清楚地说出我的问题.基本上,我有一个模板类,我需要STL algos来使用我为该类编写的(高效)交换方法.

c++ algorithm swap stl

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

移动语义==自定义交换功能已过时?

最近,许多 问题 弹出如何提供自己的swap功能.使用C++ 11,std::swap将使用std::move和移动语义以尽可能快地交换给定值.当然,这仅适用于提供移动构造函数和移动赋值运算符(或使用按值传递的运算符)的情况.

现在,有了这个,是否真的有必要swap在C++ 11中编写自己的函数?我只能想到不可移动的类型,但是再一次,自定义swaps通常通过某种"指针交换"(也就是移动)来工作.也许有某些参考变量?嗯...

c++ swap obsolete move-semantics c++11

31
推荐指数
1
解决办法
5452
查看次数

C++ 为自定义(模板)类重载 std::abs 吗?

写了我自己的数字类。超载std::numeric_limit::max()就好。然而,我正在尝试超载std::abs()但编译器不喜欢我的尝试。我试过这个:

\n
namespace std \n{\n    template<uint8_t T> \n    MyType<T> abs(const MyType<T>& mt)\n    {\n        MyType<T> copy = mt;\n        copy.val = std::abs(md.val);\n        return copy;\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

但是,编译器没有发现重载:

\n
error: no matching function for call to \xe2\x80\x98abs(const MyType<10>&)\xe2\x80\x99\n/usr/include/c++/11/bits/std_abs.h:56:3: note: candidate: \xe2\x80\x98long int std::abs(long int)\xe2\x80\x99\n   56 |   abs(long __i) { return __builtin_labs(__i); }\n      |   ^~~\n/usr/include/c++/11/bits/std_abs.h:56:12: note:   no known conversion for argument 1 from \xe2\x80\x98const MyType<10>\xe2\x80\x99 to \xe2\x80\x98long int\xe2\x80\x99\n   56 |   abs(long __i) { return __builtin_labs(__i); }\n      |       ~~~~~^~~\n/usr/include/c++/11/bits/std_abs.h:61:3: note: candidate: …
Run Code Online (Sandbox Code Playgroud)

c++ c++20

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

标签 统计

c++ ×3

swap ×2

algorithm ×1

c++11 ×1

c++20 ×1

move-semantics ×1

obsolete ×1

stl ×1