我正在学习C++,所以请耐心等待我.我有一个std::valarray在其中有double元素,我认为这是一个二维矩阵.
class Matrix {
valarray<double> elems;
int r, c;
public:
/* type? operator[](int r) { return ? } */
//...
}
Run Code Online (Sandbox Code Playgroud)
我想重载operator[],以便我可以得到一行矩阵,然后,我想要m[r][c]访问运算符.
有没有什么办法让一排,为的序列double使用std::slice的valarray,所以,如果我改变的值,它也是在矩阵变化?
我在valarray中读过这个定义:
std::slice_array<T> operator[]( std::slice slicearr );
Run Code Online (Sandbox Code Playgroud)
我operator[]必须有std::slice_array<double>&返回类型?
谢谢.
这些类之间有什么区别?这些方法与enable_if完全一样。
/// Alias of std::enable_if...
template <bool B, typename T = void>
using Enable_if = typename std::enable_if<B, T>::type;
Template<typename T, std::size_t N>
class A {
...
template <std::size_t NN = N,
typename = Enable_if<NN == 2>>
Some_Return_Type
method(param1, param2)
{}
template <std::size_t NN = N,
typename = Enable_if<NN == 1>>
Some_Return_Type
method(param1)
{}
};
Template<typename T, std::size_t N>
class B {
...
Enable_if<N == 2, Some_Return_Type>
method(param1, param2)
{}
Enable_if<N == 1, Some_Return_Type>
method(param1)
{}
};
Run Code Online (Sandbox Code Playgroud)
在以下情况下,使用enable_if的正确方法是什么:
我试图理解这段代码,但我不明白为什么这个版本
for (; first != last; ++first)
init = std::move(init) + *first;
Run Code Online (Sandbox Code Playgroud)
比这更快
for (; first != last; ++first)
init += *first;
Run Code Online (Sandbox Code Playgroud)
我确实从 std::accumulate 中取出了它们。第一个版本的汇编代码比第二个版本长。即使第一个版本创建了 init 的右值引用,它也总是通过添加 *first 来创建临时值,然后将其分配给 init,这与第二种情况下创建临时值然后将其分配给 init 的过程相同。那么,为什么使用 std::move 比使用 += 运算符“附加值”更好?
编辑
我在看C++20版本accumulate的代码,他们说在C++20accumulate之前是这个
template<class InputIt, class T>
T accumulate(InputIt first, InputIt last, T init)
{
for (; first != last; ++first) {
init = init + *first;
}
return init;
}
Run Code Online (Sandbox Code Playgroud)
在 C++20 之后它变成了
template<class InputIt, class T>
constexpr // since C++20
T accumulate(InputIt first, …Run Code Online (Sandbox Code Playgroud)