【发布时间】:2021-10-25 11:50:15
【问题描述】:
在CRTP 中,基类可以使用派生类中的函数和变量。但是,派生类的类型不能被基类直接使用,代码如下:
#include <iostream>
template <class Derived>
class A {
public:
//using Scalar = typename Derived::Scalar; // Error!
static constexpr int NA1 = Derived::NB1;
static constexpr int NA2 = Derived::NB2;
static constexpr int NA3 = Derived::NB3;
};
template <int _N = 2>
class B : public A<B<_N>> {
public:
using Scalar = double;
static constexpr int NB1 = 1;
static constexpr int NB2 = _N;
static constexpr int NB3 { sizeof(Scalar) };
};
int main(int argc, char** argv)
{
using Type = B<2>;
std::cout << Type::NA1 << ' '
<< Type::NA2 << ' '
<< Type::NA3 << '\n';
}
// output:
// 1 2 8
如果using Scalar = typename Derived::Scalar;这行没有注释,就会报错:
main.cpp:6:11: error: invalid use of incomplete type 'class B<2>'
我知道类型(Scalar)可以作为模板参数传递给基类,但是为什么不能像变量一样使用呢?这只是语言规则吗?还是有什么逻辑上的限制让这个无法实现?
【问题讨论】: