这个问题与decltype
和多重继承有关。
假设我有以下内容:
- 一个带有一些虚拟方法的抽象类 A,
- 一些派生类使用以前的虚拟方法实现方法(这些类中的每一个都是一种用例),
- 一个最终的具体类,它继承了先前用例的子集并实现了纯虚拟方法。
例如:
#include <iostream>
/**
* "Iterable container"
*/
template <class T>
struct A
{
virtual T* data() =0;
virtual const T* data() const =0;
virtual unsigned size() const =0;
T* begin() { return data(); }
T* end() { return data()+size(); }
const T* begin() const { return data(); }
const T* end() const { return data()+size(); }
};
// ------------------------------------------------------------------------
/**
* Iterative assignment
*/
template <class T>
struct B: public A<T>
{
auto operator =( const T& val ) -> decltype(*this)
{
for ( auto& v: *this ) v = val;
return *this;
}
};
/**
* Iterative display
*/
template <class T>
struct C: public A<T>
{
void show() const
{
for ( auto& v: *this )
std::cout<< v << " ";
std::cout<< std::endl;
}
};
// ------------------------------------------------------------------------
/**
* Concrete implementation
*/
template <class T, unsigned N>
struct D:
public B<T>,
public C<T>
{
using B<T>::operator=;
T dat[N];
T* data() { return dat; }
const T* data() const { return dat; }
unsigned size() const { return N; }
};
// ------------------------------------------------------------------------
int main()
{
D<double,5> d;
(d = 42).show(); // compile-time error, "no member named 'show' in 'B<double>'"
}
问题是这样的(没有双关语意);如果“用例”方法之一应该返回对 *this
的引用,我希望 this
成为对最终具体类的引用,这样我就可以将调用与其他用例中的其他方法链接起来。
然而,对于之前的实现,我遇到了编译时错误。有没有其他方法可以实现我解释的内容?
最佳答案
解决方案是使用CRTP;你告诉B
返回对 D<T, N>
的左值引用通过将派生程度最高的类型作为附加模板参数传递。
template <class T, class Derived>
struct B: public A<T>
{
auto operator =( const T& val ) -> Derived&
// ...
template <class T, unsigned N>
struct D:
public B<T, D<T, N>>,
// ...
关于c++ - 有 "dynamic decltype"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25507519/