Two possible ways to fix drawable to avoid the const problem, but not quite right.

master
Zed A. Shaw 2 months ago
parent 43e3fb8582
commit 6f346f3357
  1. 6
      meson.build
  2. 4
      sfml-const/fix1.cpp
  3. 2
      sfml-const/fix1.hpp
  4. 26
      sfml-const/fix2.cpp
  5. 27
      sfml-const/fix2.hpp
  6. 2
      sfml-const/original.cpp

@ -54,6 +54,10 @@ executable('sfml-original', 'sfml-const/original.cpp',
override_options: exe_defaults,
dependencies: dependencies)
executable('sfml-fixed1', 'sfml-const/fixed.cpp',
executable('sfml-fix1', 'sfml-const/fix1.cpp',
override_options: exe_defaults,
dependencies: dependencies)
executable('sfml-fix2', 'sfml-const/fix2.cpp',
override_options: exe_defaults,
dependencies: dependencies)

@ -1,9 +1,9 @@
#include <iostream>
#include "constness.hpp"
#include "fix1.hpp"
using std::cout;
void Shape::draw(RenderTarget& target) const {
void Shape::draw(RenderTarget& target) {
cout << "shape draw\n";
}

@ -12,5 +12,5 @@ class Drawable {
class Shape : public Drawable {
public:
void draw(RenderTarget& target) const override;
void draw(RenderTarget& target) override;
};

@ -0,0 +1,26 @@
#include <iostream>
#include "fix2.hpp"
using std::cout;
void RenderTarget::draw(const Drawable& drawable) {
drawable.draw(*this);
}
void Shape::draw(RenderTarget& target) const {
cout << "shape draw\n";
}
void Shape::render_to(RenderTarget &target) {
cout << "shape render_to instead\n";
}
int main() {
RenderTarget target;
Shape shape;
target.draw(shape);
shape.render_to(target);
return 0;
}

@ -0,0 +1,27 @@
#pragma once
class Drawable;
class RenderTarget {
public:
void draw(const Drawable& drawable);
};
class Drawable {
public:
/*
* NOTE: This requires const because RenderTarget
* pass itself in as a *this which is always const.
* If you need to draw without const then invert it
* then use shape.render_to(target) instead.
*/
virtual void draw(RenderTarget& target) const = 0;
virtual void render_to(RenderTarget& target) = 0;
};
class Shape : public Drawable {
public:
void draw(RenderTarget& target) const override;
void render_to(RenderTarget &target) override;
};

@ -1,5 +1,5 @@
#include <iostream>
#include "constness.hpp"
#include "original.hpp"
using std::cout;

Loading…
Cancel
Save