【问题标题】:How to implement an interpolatable interface in C++如何在 C++ 中实现可插值接口
【发布时间】:2015-03-10 09:30:10
【问题描述】:

我正在尝试实现软件渲染器,它在顶点着色之后发生插值

以下是它的声明

template <class T>
class Interpolatable
{
    // The function calculates an interpolated value
    // along the fraction t between 0.0 and 1.0. 
    // When t = 1.0, endValue is returned.
    virtual T interpolate(const T &endValue, float t)=0;
};

struct Vertex: public Interpolatable<?????????>
{
    float x, y, z;

    Vertex()=default;
    Vertex(float, float, float);

    virtual Vertex &interpolate(const Vertex &endValue, float t) const;
};

是否可以让 Vertex 的 interpolate 方法返回 Vertex 的实例? 编译器总是给我错误

【问题讨论】:

  • struct Vertex: public Interpolatable 你想使用 CRTP 吗?
  • struct Vertex: interpolatable&lt;Vertex&gt; 应该可以工作。注意你需要返回Vertex不是 Vertex&amp;
  • 您似乎错过了T const&amp; beginValue 以返回t==0 案件。

标签: c++ templates inheritance interface


【解决方案1】:

您可以安全地将类的名称作为模板参数传递,但您遇到的任何错误都是由于函数签名不匹配造成的。

struct Vertex: public Interpolatable<Vertex>

virtual T interpolate(const T &endValue, float t)=0;
virtual Vertex &interpolate(const Vertex &endValue, float t) const;
//             ^reference                                      ^declared const

看来你的签名应该是:

virtual T interpolate(const T &endValue, float t) const =0;
virtual Vertex interpolate(const Vertex &endValue, float t) const;

【讨论】:

    【解决方案2】:

    如果你修复了三个错误,它应该可以工作:

    • ????????? 应该是 Vertex
    • interpolate 应该按值返回 Vertex
    • interpolate 不应为 const(或应为基类中的 const

    【讨论】:

    • 可以同时声明纯虚方法和const方法吗?
    • 是的,void foo() const =0;
    • 可以,但是改变=0和const的顺序是非法的
    • @TimHsu:是的,你需要按照正确的顺序排列它们,就像 TartanLlama 所做的那样。
    猜你喜欢
    • 2020-04-30
    • 2013-11-27
    • 1970-01-01
    • 2012-04-03
    • 2022-01-16
    • 2023-03-25
    • 2012-02-01
    • 2011-03-03
    相关资源
    最近更新 更多