c++ - 返回派生类型实例的 CRTP 和函数

标签 c++ inheritance crtp

我正在尝试创建一个基类,其函数在继承时会返回子类的实例。我目前正在尝试的抽象版本:

A.h:

#include <string>    

template <typename Derived>
class A {

public:
    A<Derived>();

    Derived Append(wchar_t the_char) const;

protected:
    std::wstring some_string;

} // class A

A.cpp:

#include "A.h"

A<class Derived>::A() {}

Derived A::Append(wchar_t the_char) const
{
    Derived d(some_string);
    d.some_string += the_char;
    return d;
}

B.h:

class B : public A<B>
{
public:
    B();
};

B.cpp:

B::B() : A() {}

我希望能够用它来做如下事情:

B theObj;
theObj = theObj.Append(L'h');

但是,我无法找到一种组织代码来实现此目的的方法。我不确定这里是否需要某种形式的前向声明(forward declaration)或什么。尝试了几件事,但没有任何运气。想法?

最佳答案

您在寻找这种语法吗?

template<class Derived>
Derived A<Derived>::Append(wchar_t the_char) const
{
    Derived d(some_string);
    d.some_string += the_char;
    return d;
}

将它放在 cpp 文件中不会有太大好处。您最好将它添加到头文件或创建其他一些您可以包含的文件(MS 有时称为 .inl)以使其用户可以访问它。

关于c++ - 返回派生类型实例的 CRTP 和函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36922490/

相关文章:

c++ - vector 删除功能删除错误的对象

c++ - 关于指针和引用

c++ - 从派生类访问 protected 函数

c++ - 如果使用 CRTP,如何在存在的情况下调用派生函数,否则使用默认值?

c++ - 防止用户从不正确的 CRTP 基础派生

c++ - vector<unique_ptr<X>> v 出错

c++ - 为什么我的程序在分配更多线程的情况下执行时间更长?

css - 可以:before and :after pseudo-elements inherit height from the parent element?

c# - 跨不同(共享)项目和命名空间的继承

javascript - 如何通过原型(prototype)实现经典的类继承