c++ - 有 "dynamic decltype"吗?

标签 c++ c++11 multiple-inheritance decltype

这个问题与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/

相关文章:

c++ - int 可以别名为 unsigned int 吗?

c++ - 需要对条件变量寻求的互斥保护(原子)赋值吗?

c++ - 在带有 boost::function 的 std::for_each 中使用 boost.lambda

python 3.7.4 : inheriting both ABC and concrete class

c++ - 从 C++11 可变参数模板参数中消除重复项

c++ - 我需要一个正则表达式来标记 C++ 中引号内的多个单词

c++ - 具有灵活数组成员的结构的大小

c++ - 我如何告诉 clang-format 缩进可见性修饰符?

c++ - boost 序列化 - 序列化 std::tr1::shared_ptr?

Python - 如何让多重继承发挥作用?