编译器 VS2017。
有一个有效的代码:
#include "pch.h"
#include <iostream>
using namespace std;
template <class T> class a {
int aint;
T* tptr;
public:
a(T* ptr1) :tptr(ptr1) {}
};
class b:public a<b> {
int bint;
public:
b() :a(this) {}
void print() { cout <<endl<<"run class b"; }
};
int main()
{
cout << endl<<"Hello World!";
b bb;
bb.print();
}
现在我想让它从类“b”传递this指针,而不是通过类“a”的构造函数,而是通过模板参数。我写的是这样的:
#include "pch.h"
#include <iostream>
using namespace std;
class b;
template <class T* ttptr> class a {
int aint;
T* tptr;
public:
a() :tptr(ttptr){}
};
class b :public a <this> {
int bint;
public:
b() {}
void print() { cout <<endl<<"run class b"; }
};
int main()
{
cout << endl<<"Hello World!";
b bb;
bb.print();
}
但是编译器发誓:
class b :public a <this>
问题:
- 是否可以通过模板参数传递 this 指针?
- 如果可能,该怎么做?
- 如果不是,为什么不呢?
this永远不会被认为是编译时常量,所以你不能。我根本不明白它是如何工作的。此外,
this没有外部非静态函数。它可以更容易地完成。在内部,您可以在via
a<T>中向下转换,因此不需要将指针存储在类字段中。thisT *static_cast<T *>(this)