【发布时间】:2018-09-14 08:38:01
【问题描述】:
我正在使用 CRPT,需要访问派生类中定义的基类中的参数。它在成员函数中使用时起作用,但在(我猜的)编译时表达式中不起作用(定义类型时会出现问题)。下面的代码说明了这个问题:
#include <iostream>
#include <array>
template <typename impl_t>
struct base {
// no complaints
void print () {
std::cout << "Base, impl_t::i_q = " << impl_t::i_q << std::endl;
}
// compiler error:
// clang++: no member named 'i_q' in 'deriv_t'
// g++: incomplete type ‘deriv_t’ used in nested name specifier
using vec_t = std::array<double, impl_t::i_q>;
};
struct deriv_t : public base<deriv_t> {
static const std::size_t i_q = 1;
};
int main () {
deriv_t d;
d.print();
}
我只是想知道这里违反了哪些规则?我想出的解决方案是在模板中定义i_q和impl_t,但想知道是否有更整洁的方法来解决问题。
解决方案:
感谢 Evg,这是解决方案:
template <typename impl_t>
struct traits;
template <typename impl_t>
struct base_t {
void print () {
std::cout << "Base, impl_t::i_q = " << traits<impl_t>::i_q << std::endl;
}
using vec_t = std::array<double, traits<impl_t>::i_q>;
};
struct deriv_t;
template <>
struct traits<deriv_t> {
static const std::size_t i_q = 1;
};
struct deriv_t : public base_t<deriv_t> {
};
【问题讨论】: