我知道这不能编译,并且我知道“DerivedTemplate”类型不能直接实现抽象成员函数。我想知道的是为什么,即什么规则阻止了此工作?

#include <iostream>
#include <memory>

template<typename DuplicateType, typename DuplicatedReturnType = DuplicateType>
struct EnableDuplication
{
    virtual ~EnableDuplication()
    {}
    virtual std::unique_ptr<DuplicatedReturnType> duplicate() const
    {
        std::cout << "Using the templated duplication." << std::endl;
        const auto& thisObj{static_cast<const DuplicateType&>(*this)};
        return std::make_unique<DuplicateType>(thisObj);
    }
};

struct Base
{
    Base(int value) : value_(value)
    {}
    virtual ~Base()
    {}
    virtual std::unique_ptr<Base> duplicate() const =0;

    const int value_;
};

struct DerivedTemplate : Base, EnableDuplication<DerivedTemplate, Base>
{
    DerivedTemplate(int value) : Base(value)
    {}
};

struct DerivedImplement : Base
{
    DerivedImplement(int value) : Base(value)
    {}
    virtual std::unique_ptr<Base> duplicate() const override
    {
        std::cout << "Using the implented duplication." << std::endl;
        return std::make_unique<DerivedImplement>(*this);
    }

};

void printValue(const Base& original, const std::unique_ptr<Base>& copy)
{
    std::cout << "Value of derived is: " << original.value_ <<
        "\nValue of copy is: " << copy->value_ << std::endl;
}

int main(int argc, const char* argv[])
{
    DerivedTemplate dt{5};
    auto copyt{dt.duplicate()};
    printValue(dt, copyt);

    DerivedImplement di{5};
    auto copyi{di.duplicate()};
    printValue(di, copyi);
    return 0;
}

最佳答案

它无法编译,因为DerivedTemplate源自Base,但尚未实现纯虚函数:

virtual std::unique_ptr<Base> duplicate() const =0;

如果实现上述功能,它将起作用:
struct DerivedTemplate : Base, EnableDuplication<DerivedTemplate, Base>
{
    DerivedTemplate(int value) : Base(value)
    {}

    virtual std::unique_ptr<Base> duplicate() const override
    {
        std::cout << "DerivedTemplate::duplicate()\n";
        return std::make_unique<DerivedTemplate>(*this);
    }
};

Demo

关于c++ - 通过C++模板复制派生对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35289322/

10-10 09:23