我正试着绕着CRTP.有一些很好的资料来源,包括这个论坛,但我认为我对静态多态性的基础知识有些困惑.查看以下维基百科条目:
template <class T>
struct Base
{
void implementation()
{
// ...
static_cast<T*>(this)->implementation();
// ...
}
static void static_func()
{
// ...
T::static_sub_func();
// ...
}
};
struct Derived : public Base<Derived>
{
void implementation();
static void static_sub_func();
};
Run Code Online (Sandbox Code Playgroud)
我理解这有助于我在派生类中使用不同的implementation()变体,有点像编译时虚函数.但是,我的困惑是我觉得我不能有像这样的功能
void func(Base x){
x.implementation();
}
Run Code Online (Sandbox Code Playgroud)
就像我使用普通继承和虚函数一样,由于Base被模板化,但我必须指定
func(Derived x)
Run Code Online (Sandbox Code Playgroud)
或使用
template<class T>
func(T x)
Run Code Online (Sandbox Code Playgroud)
那么CRTP实际上在这个上下文中给我带来了什么,而不是简单地在Derived :: Base中简单地隐藏/实现该方法?
struct Base
{
void implementation();
struct Derived : public Base
{
void implementation();
static void static_sub_func();
};
Run Code Online (Sandbox Code Playgroud) 如果这是一个微不足道的问题,请原谅我,我只是在学习 C++,并试图理解某些概念。尤其是当涉及到迭代器时,我完全迷失了。
假设我有一个表示某种数据结构的自定义类,其成员之一是整数向量。我想为该类编写一个双向迭代器,它仅输出向量中的偶数。有没有简单且有启发性的方法?我不想使用 STL 以外的库。
如果有人能启发我这里发生了什么,我将不胜感激:假设我声明以下内容
class Base {
public:
virtual void member(Base b) = 0;
};
Run Code Online (Sandbox Code Playgroud)
这给出了以下编译器错误:
pvf.cpp:3:18: error: cannot declare parameter ‘b’ to be of abstract type ‘Base’
virtual void member(Base b) = 0;
^
pvf.cpp:1:7: note: because the following virtual functions are pure within ‘Base’:
class Base {
^
pvf.cpp:3:18: note: virtual void Base::member(Base)
virtual void member(Base b) = 0;
Run Code Online (Sandbox Code Playgroud)
但是,如果我通过引用传递,它编译没有问题:
class Base {
public:
virtual void member(Base& b) = 0;
};
Run Code Online (Sandbox Code Playgroud)
此外,我想在派生类中实现 member() 作为
class Base {
public:
virtual void member(Base& …Run Code Online (Sandbox Code Playgroud) 我知道这可能是一个常见的问题,我之前看过类似的问题.我试图围绕"返回const引用"的东西.我似乎陷入了这个看似简单的例子:
#include <iostream>
using namespace std;
class Test {
public:
int x;
Test(): x(0) {};
const int& getX() const {
return x;
}
};
int main() {
Test t;
int y = t.getX();
cout << y << endl;
t.x = 1;
cout << y << endl; // why not 1?
}
Run Code Online (Sandbox Code Playgroud)
我明白通过const int返回并阻止我使用类似的设置tx y=1,这很好.但是,我希望y在最后一行中为1,但它保持为零,就像getX()返回一个普通的int一样.到底发生了什么?
我有两个文件,file1.csv
3 1009
7 1012
2 1013
8 1014
Run Code Online (Sandbox Code Playgroud)
和file2.csv
5 1009
3 1010
1 1013
Run Code Online (Sandbox Code Playgroud)
在shell中,我想根据第二列中的标识符,从第一个文件中减去第二个文件中第一列中的计数.如果第二列中缺少标识符,则假定计数为0.
结果将是
-2 1009
-3 1010
7 1012
1 1013
8 1014
Run Code Online (Sandbox Code Playgroud)
文件很大(几GB).第二列已排序.
我如何在shell中有效地做到这一点?