C++ implicitly transform trivially constructable struct to member - c++

I feel that its unlikelier than not, but I'd like to see if a function can deduce its parameters from a trivially wrapped struct. For example:
struct wrapped_float
{
float f;
wrapped_float(float f) : f(f) {}
};
float saxpy(float a, float x, float y)
{
return a * x + y;
}
int main()
{
wrapped_float a = 1.1, x = 2.2, y = 3.3;
auto result = saxpy(a, x, y); // ofc compile error
}
The motivation behind this is to make a lightweight wrapper around GDI calls with device context handles (HDC). There exists a lot of legacy code which uses HDCs and I'd like to refactor a lot of this code incrementally. My strategy is to make a lightweight wrapper around HDC like this:
#include <Windows.h>
struct graphics
{
HDC dc;
graphics(HDC dc) : dc(dc) {}
void rectangle(int x, int y, int w, int h)
{
Rectangle(dc, x, y, x + w, y + h);
}
};
void OnPaint(HDC dc)
{
Rectangle(dc, 1, 2, 3, 4);
}
int main()
{
HDC dc;
// setup dc here
graphics g = dc;
OnPaint(g);
}
So that if g can be implicitly transformed to HDC, then all legacy code will normally compile, but I can slowly refactor code to become like this:
void OnPaint(graphics g)
{
g.rectangle(1, 2, 3, 4);
}
Any recommendations are also welcome since this simply might not be possible in C++ (or any programming language).

From the comments, I was not aware that C++ had a casting operator. The simple solution is to add:
struct graphics
{
HDC dc;
graphics(HDC dc) : dc(dc) {}
void rectangle(int x, int y, int w, int h)
{
Rectangle(dc, x, y, x + w, y + h);
}
operator HDC()
{
return dc;
}
};

Related

C++ Object referencing in different scopes

I have a class Rect such that it holds the width, height, x and y values of a shape. The class can draw using the values in the parameter and move the drawn rect.
Rect::Rect(w, h, x, y, const std::string &image_path) : _w(w), _h(h),
_x(x), _y(y)
{
SDL_Surface *surface = IMG_Load(image_path.c_str());
if (!surface) {
std::cerr << "Failed to create surface.";
}
//create texture
texture = SDL_CreateTextureFromSurface(Window::renderer, surface);
if (!texture) {
std::cerr << "Failed to create worker texture.";
}
SDL_FreeSurface(surface);
}
Rect::~Rect()
{
SDL_DestroyTexture(texture);
}
Rect::draw()
{
//where the constructor parameters are parsed
SDL_Rect rect= {_x, _y, _w, _h} ;
//extra code about some SDL texture stuff and RenderCopy
}
Rect::moveX(int x){
_x +=x;
}
In my Unit class, I include the class Rect and I create my units, draw them in the same function. There is another function in unit that moves rect by checking another value from another class that changes.
Unit::Unit()
Unit::~Unit()
void Unit::createUnit(int type, int x, int y){
if (type == 0)
{
Rect unit1(unitImageWidth, unitImageSizeHeight, x, y, "res/unit1.png");
}
if (type == 1)
{
Rect unit2(unitImageWidth, unitImageSizeHeight, x, y, "res/unit2.png");
}
}
void Unit::moveUnit(int x){
if(selection == 0)
{
unit1.movex(x);
}
if (selection == 1)
{
unit2.movex(x);
}
}
My question is:
When in Unit::moveUnit(), how can I reference the object Rect "unit1" and Rect "unit2" that are initialized in Unit::createUnit()?
When I try to compile, it say that unit1 and unit2 are undefined.
You can't do what you want to do. Non-static local variables are bound to their scope. They are only visible inside and are destroyed when the program exits the area bounded by the {} braces.
The simplest solution is to go in a completely different direction. Add to Unit a private variable to contain the Rect for example,
Rect sprite;
Then replace
void createUnit(int type, int x, int y);
with a Unit constructor
Unit(int type, int x, int y);
And implement the constructor something like
Unit::Unit(int type, int x, int y): sprite(unitImageWidth,
unitImageSizeHeight,
x,
y,
type == 0? "res/unit1.png": "res/unit2.png")
{
}
The colon : starts a Member Initializer List and that crazy ?: Is a one line if statement called the Ternary or Conditional Operator
Note: I don't know what unitImageWidth and unitImageSizeHeight are or where they come from. Make sure you do and make sure they are accessible.
moveUnit becomes
void Unit::moveUnit(int x)
{
sprite.movex(x);
}
because sprite knows what it is and what image has been loaded and can move the Rect to x (or whatever movex does).
To use you
Unit myUnit(0, 1024, 42); // creates a unit of type 0 at coordinates 1024,42
myUnit.movex(88); // moves myUnit to 88,42 (I think)
Just add two Rect members in your class Unit, then you can use it in different member functions.
Better using pointer, as below:
class Unit
{
public:
Unit::Unit()
: uint1(NULL), uint2(NULL){};
Unit::~Unit()
{
if (uint1 != NULL) {
delete unit1;
uint1 = NULL;
}
if (uint2 != NULL) {
delete unit2;
uint2 = NULL;
}
};
void Unit::createUnit(int type, int x, int y)
{
if (type == 0) {
unit1 = new Rect(unitImageWidth, unitImageSizeHeight, x, y, "res/unit1.png");
}
if (type == 1) {
unit2 = new Rect(unitImageWidth, unitImageSizeHeight, x, y, "res/unit2.png");
}
}
void Unit::moveUnit(int x)
{
if (selection == 0) {
unit1->movex(x);
}
if (selection == 1) {
unit2->movex(x);
}
}
private:
Rect *unit1;
Rect *unit2;
};

c++ pointer to member function, replacement for __closure

Some time ago, Borland have introduced in their BCB evironment an extension to C++ language. This extension is a __closure keyword. The question is, if it is possible to implement such functionality in plain C++ or C++11? If you are not familiar with __closure keyword, below code provides explanation in comments.
Thanks in advance!
Toreno
#include <stdio.h>
// __closure keyword is used here !
typedef void (__closure * MemberCallback)(int x, int y, int z);
class A
{
private:
MemberCallback callback;
public:
A() : callback(NULL)
{
}
void setCallback(MemberCallback newCallback)
{
callback = newCallback;
}
void call(int x, int y, int z)
{
if(callback)
callback(x, y, z);
else
printf("NOT SET(%i, %i, %i)\n", x, y, z);
}
};
class B
{
public:
void func1(int x, int y, int z)
{
printf("FUNC 1(%i, %i, %i)\n", x, y, z);
}
void func2(int x, int y, int z)
{
printf("FUNC 2(%i, %i, %i)\n", x, y, z);
}
};
int main()
{
// A and B classes do not know about each other. There is no possibility
// to for inheritance because B class can implement multiple instances
// of callback function
A a;
B b;
a.call(1, 2, 3); // Prints: NOT SET(1, 2, 3)
a.setCallback(b.func1);
a.call(4, 5, 6); // Prints: FUNC 1(4, 5, 6)
a.setCallback(b.func2);
a.call(7, 8, 9); // Prints: FUNC 2(7, 8, 9)
return 0;
}
std::function is exactly what you're looking for. If you want to learn how such mechanism is actually implemented in the library, here's a good series of blog posts on it. Combine that with lambda functions for capturing of local variables.
Re-hash of the previous answer with the full code, for others like me that want a quick reference to a common pattern:
#include <functional>
#include <stdio.h>
// __closure replacement
typedef std::function<void(int x, int y, int z)> MemberCallback;
class A
{
public:
void setCallback( MemberCallback newCallback ) {
callback_ = newCallback;
}
void call( int x, int y, int z ) {
if ( callback_ )
callback_( x, y, z );
else
printf( "NOT SET(%i, %i, %i)\n", x, y, z );
}
private:
MemberCallback callback_;
};
class B
{
public:
void func1( int x, int y, int z ) {
printf( "FUNC 1(%i, %i, %i)\n", x, y, z );
}
void func2( int x, int y, int z ) {
printf( "FUNC 2(%i, %i, %i)\n", x, y, z );
}
};
int main( )
{
// A and B classes do not know about each other. There is no possibility
// to for inheritance because B class can implement multiple instances
// of callback function
A a;
B b;
a.call( 1, 2, 3 ); // Prints: NOT SET(1, 2, 3)
a.setCallback( [&b](int x, int y, int z){ b.func1(x, y, z); } );
a.call( 4, 5, 6 ); // Prints: FUNC 1(4, 5, 6)
a.setCallback( [&b](int x, int y, int z){ b.func2(x, y, z); } );
a.call( 7, 8, 9 ); // Prints: FUNC 2(7, 8, 9)
return 0;
}
Output:
NOT SET(1, 2, 3)
FUNC 1(4, 5, 6)
FUNC 2(7, 8, 9)

Draw function timer openframeworks

How can I, using the draw() function of openframeworks, draw a square - ofRect (x, y, w, h) for x in x seconds?
I know it is possible since the draw uses fps but I do not know how to manipulate in order to do what I want.
Thank you!
One option is to interpolate based on time, not frame count using ofGetElapsedTimeMillis()
Another is to use a tweening/animation addon. You can find quite a few on ofxAddons in the animation section
You could do that in the simplest way:
int x = ofGetElapsedTimeMillis();
int y = 10;
int w = 100;
int h = 100;
ofDrawRectangle(x, y, w, h);
Note that in OpenFrameworks you should use ofDrawRectangle, it is different from ofRectangle.
If you want to reach more adivanced animations, I would recommend you to use ofxTweenzor addon, where you can manipulate variables in a period of time like this:
.h file:
#include "ofMain.h"
#include "ofxTweenzor.h"
class ofApp : public ofBaseApp{
public:
void setup();
void update();
void draw();
float x1;
};
.cpp file:
#include "testApp.h"
void ofApp::setup() {
Tweenzor::init();
float initialX = 0.f;
float finalX = 900.f;
float delay = 0.0f;
float durationInSeconds = 1.f;
Tweenzor::add(&x, initialX, finalX, delay, durationInSeconds );
}
void ofApp::update(){
Tweenzor::update( ofGetElapsedTimeMillis() );
}
void ofApp::draw() {
int y = 10;
int w = 100;
int h = 100;
ofDrawRectangle(x, y, w, h);
}

Confused with variables in classes

I'm a bit confused with classes was hoping some one could explain.
I have a class I'm making to create buttons for a game menu. There are four variables:
int m_x
int m_y
int m_width
int m_height
I then want to use a render function in the class but Im not understanding how i use the 4 int variables in the class and pass it to the function in the class?
My class is like this:
class Button
{
private:
int m_x, m_y; // coordinates of upper left corner of control
int m_width, m_height; // size of control
public:
Button(int x, int y, int width, int height)
{
m_x = x;
m_y = y;
m_width = width;
m_height = height;
}
void Render(SDL_Surface *source,SDL_Surface *destination,int x, int y)
{
SDL_Rect offset;
offset.x = x;
offset.y = y;
SDL_BlitSurface( source, NULL, destination, &offset );
}
} //end class
Where i am confused is how the values created in public:Button is passed to void render I'm not fully sure I've got this right, if i have its pure luck so far because I'm still a little bit confused.
Maybe an example will help:
#include <iostream>
class Button
{
private:
int m_x, m_y; // coordinates of upper left corner of control
int m_width, m_height; // size of control
public:
Button(int x, int y, int width, int height) :
//This is initialization list syntax. The other way works,
//but is almost always inferior.
m_x(x), m_y(y), m_width(width), m_height(height)
{
}
void MemberFunction()
{
std::cout << m_x << '\n';
std::cout << m_y << '\n';
//etc... use all the members.
}
};
int main() {
//Construct a Button called `button`,
//passing 10,30,100,500 to the constructor
Button button(10,30,100,500);
//Call MemberFunction() on `button`.
//MemberFunction() implicitly has access
//to the m_x, m_y, m_width and m_height
//members of `button`.
button.MemberFunction();
}
You might want to spend some time learning C++ before getting too deep into a complex programming project.
To answer your question, The variables initialized in the constructor (Button) are part of the class instance. So they're available within any class method, including Render.

using operators inside class or struct?

OK so I am working on some game logic, I have done a fair bit of research (as much as the internet will allow) and still don't have a solid understanding of class and struct so please go gentle!
Basically, I want to be able to create an object with the properties all on one line ie.
object a{1, 1, 50, 15, 5}; // create object a
and I want some extra stuff to be made up aswell like:
class object
{
public:
int x;
int y;
int h;
int w;
int s;
int x1;
int y1;
int ps;
int ns;
int x1 = x + w;
int y1 = y + h;
int ps = 0 + s;
int ns = 0 - s;
};
I don't know which language you're working with, but it looks a bit like C++, so here's an example:
class Rect
{
public:
int x, y;
int w, h;
int right, bottom;
// This method is called a constructor.
// It allows you to perform tasks on
// the instantiation of an object.
Rect(int x_, int y_, int w_, int h_)
{
// store geometry
this->x = x_;
this->y = y_;
this->w = w_;
this->h = h_;
// calculate sides
this->right = x_ + w_;
this->bottom = y_ + h_;
}
};
// You use the constructor in your main() function like so:
Rect myObject(1, 1, 50, 15);
// And you can access the members like so:
myObject.x = 10;
myObject.right = myObject.x + myObject.w;
You cannot use operators inside the definition of a class as you proposed in your question. Operations on variables must take place inside a constructor (or other method).