【发布时间】:2014-10-19 21:05:55
【问题描述】:
这个问题与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 成为对最终具体类的引用,以便我可以将调用与来自其他用例的其他方法链接起来.
但是,使用以前的实现,我得到一个编译时错误。还有其他方法可以实现我所解释的吗?
【问题讨论】:
标签: c++ c++11 multiple-inheritance decltype