No matching function call when using vector push_back - c++

Im using SFML and its Vector2f as well as a normal c++ vector.
Im using a class called projectiles, within is a default constructor and
///////////////////////////////////
// Construct with position and velocities
//////////////////////////////////
projectile::projectile(const sf::Vector2f itsPosition, const sf::Vector2f itsVel):
position(itsPosition),
vel(itsVel)
{}
the call comes from main in the form of
if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
{
projectiles.push_back(sf::Vector2f(rectPos), sf::Vector2f(10,10));
}
leading to the error
no matching function for call to 'std::vector<projectile>::push_back(sf::Vector2<float>, sf::Vector2<float>)'|
do I need to let it initialize with the default constructor then edit after or is there something simple I'm missing here

Your issue is that you are passing two arguments to the push_back method, which is defined as only taking one argument. There is literally no definition for that function with more than one argument, so the compiler complains that you are looking for a method that doesn't exist. Source: (http://www.cplusplus.com/reference/vector/vector/push_back/)
What you actually need to do, is construct a new projectile, and then pass it back.
As immibis stated in his comment on your question, there is another method that might do what you want, emplace_back(). You may want to try changing the method to that instead. I've never used that method, so I can't say much beyond that. Source: (http://www.cplusplus.com/reference/vector/vector/emplace_back/)

Related

Modifying non const attribute in const function

So I have a class with the following function :
void AddNoiseToAim(Vector2D& position) const which is essentialy a utility function.
To correctly compute the noise I use a complexe object which require kind of a heavy initialisation so to avoid doing it at every call of the function, I decided to put the object as a non const attribute of the class so the initialisation is performed once at the instantiation and then used multiple time by the function.
The problem is that AddNoiseToAim is const and the attribute is not so I can't use it in the function, BUT the attribute is only used for this specific purpose so the only thing that retain me from putting it in the scope of the function is the initialisation of the object.
I thought of 3 solutions for now, the first one is to remove the const modifier of the AddNoiseToAim but I don't want to do that, since by nature this function doesn't modify the instance of the class. Second solution would be to pass the attribute as a reference to the function like it's done for the parameter position, but even that feel kind of weird, since it's like making a detour. Finally the solution I've gone with for now but which would give me memory issues is doing something like that :
void Raven_WeaponSystem::AddNoiseToAim(Vector2D& AimingPos) const
{
static FuzzyModule* fuzzyModule = InitializeFuzzyModule();
/* omitted */
}
FuzzyModule is not an attribute of the class anymore.
In my case Raven_WeaponSystem has the same life span as the application, so I don't really care about the lost memory but it really doesn't feel good.
To sum up ! I would like the function to initialize an object in its scope only once at the first call of the function OR I would like the object to be initialize outside of the function and used in the constant function (in which case my second solution should suffice).
Thanks for your time ! Cheers.
If you can't initialize fuzzyModule in the constructor, declare it mutable in the class (which will allow you to modify its value in a const function).
mutable FuzzyModule *fuzzyModule;

How can I make a class that type-erases objects until a function is called on them without specifying the list of possible functions up front?

Background
The title probably sounds confusing, so let me explain. First of all, here is a minimal version of my implementation, so you can follow along with the concepts more easily. If you've seen some of Sean Parent's talks, you'll know he came up with a way to abstract polymorphism, allowing code such as this:
std::vector<Drawable> figures{Circle{}, Square{}};
for (auto &&figure : figures) {draw(figure);}
Notice that there are no pointers or anything. Calling draw on a Drawable will call the appropriate draw function on the contained object without the type of the object being easily accessible. One major downside to this is that similar classes to Drawable have to be written for each task. I'm trying to abstract this a bit so that the function does not have to be known by the class. My current solution is as follows:
std::vector<Applicator<Draw>> figures{Circle{}, Square{}};
for (auto &&figure : figures) {figure.apply(Draw{});}
Here, Draw is a functor with an operator()(Circle) and opeator()(Square), or a generic version. In this way, this is also sort of a visitor pattern implementation. If you wanted to also, say, print the name of each figure, you could do Applicator<Draw, PrintName>. When calling apply, the desired function is chosen.
My implementation works by passing a boost::variant of the callable types to the virtual function and having it visit that variant and call the function within. Overall, I would say this implementation is acceptable, but I haven't yet thought much about allowing any number of parameters or a return type, let alone ones that differ from function to function.
Question
I spent days trying to think of a way to have this work without making Applicator a template. Ideally, the use would be more similar to this. For the sake of simplicity, assume the functions called must have the signature void(ObjectType).
//For added type strictness, I could make this Applicator<Figure> and have
//using Figure<struct Circle> = Circle; etc
std::vector<Applicator> figures{Circle{}, Square{}};
for (auto &&figure : figures) {figure.apply(Draw{});} //or .apply(draw); if I can
The problem usually comes down to the fact that the type of the object can only be obtained within a function called on it. Internally, the class uses virtual functions, which means no templates. When apply is called, here's what happens (identical to Sean's talks):
The internal base class's apply is called on a pointer to the base class with the runtime type of a derived class.
The call is dispatched to the derived class, which knows the type of the stored object.
So by the time I have the object, the function to call must be reduced to a single type known within the class that both knows which function to call and takes the object. I cannot for the life of me come up with a way to do this.
Attempts
Here are a couple of failed attempts so you can see why I find this difficult:
The premise for both of the first two is to have a type that holds a function call minus the unknown first argument (the stored object). This would need to at least be templated on the type of the callable object. By using Sean Parent's technique, it's easy enough to make a FunctionCall<F> class that can be stored in a GenericFunctionCall, much like a Circle in a Figure. This GenericFunctionCall can be passed into the virtual function, whereas the other cannot.
Attempt 1
apply() is called with a known callable object type.
The type of the callable object is used to create a FunctionCall<Type> and store it as a type-erased GenericFunctionCall.
This GenericFunctionCall object is passed to the virtual apply function.
The derived class gets the call object and has the object to be used as the first argument available.
For the same reason of virtual functions not being allowed to be templates, the GenericFunctionCall could call the necessary function on the right FunctionCall<Type>, but not forward the first (stored object) argument.
Attempt 2
As a continuation of attempt 1:
In order to pass the stored object into the function called on the GenericFunctionCall, the stored object could be type-erased into a GenericObject.
One of two things would be possible:
A function is called and given a proper FunctionCall<Type>, but has a GenericObject to give to it, with the type unknown outside of a function called on it. Recall that the function cannot be templated on the function call type.
A function is called and given a proper T representing the stored object, but has a GenericFunctionCall to extract the right function call type from. We're back where we started in the derived class's apply function.
Attempt 3
Take the known type of a callable object when calling apply and use it to make something that stores a function that it can call with a known stored object type (like std::function).
Type-erase that into a boost::any and pass it to the virtual function.
Cast it back to the appropriate type when the stored object type is known in the derived class and then pass the object in.
Realize that this whole approach requires the stored object type to be known when calling apply.
Are there any bright ideas out there for how to turn this class into one that doesn't need the template arguments, but can rather take any callable object and call it with the stored object?
P.S. I'm open for suggestions on better names than Applicator and apply.
This is not possible. Consider a program composed of three translation units:
// tu1.cpp
void populate(std::vector<Applicator>& figures) {
figures.push_back(Circle{});
figures.push_back(Square{});
}
// tu2.cpp
void draw(std::vector<Applicator>& figures) {
for (auto &&figure : figures) { figure.apply(Draw{}); }
}
// tu3.cpp
void combine() {
std::vector<Applicator>& figures;
populate(figures);
draw(figures);
}
It must be possible for each TU to be translated separately, indeed in causal isolation. But this means that at no point is there a compiler that simultaneously has access to Draw and to Circle, so code for Draw to call Circle::draw can never be generated.

How to present gravity in 2D (Euler's method) without using any additional libraries?

My last question remains unanswered, but I think I'm kind of on a right way this time.
What I need to achieve is a model of gravity, in 2D plane only. I need to have a class of a celestial body, with positionX, positionY, velocity vector and a mass. I want it to work like that: everytime I add a new body, its mass and initial velocity (if set) have an effect on all the other bodies, affecting their position and velocity accordingly. I have been told that it's best to use a list for that and everytime I create a new object I'll apply a move() method to every other list element. Is that right? (clarified because of o_weisman comment, thanks!)
I've declared the class (not all the variables are there)
class CBody
{
protected:
double x;
double y;
double mass;
public:
void move(double time, list<CBody> CBodyList);
CBody();
~CBody();
};
but I am unable to come up with the right method how to exactly make the new list object's values alter the position (by move() method) of the previous ones and represent it in time.
Do you have any ideas? Basically what I want to achieve is that whenever I add a new object with given values (I'm using rand() right now, but I'll probably use cin>>stuff later) it triggers a move() method inside every previous celestial body and adjusts their position accordingly. The problem is - it's not a fixed state, it's happening all the time, how to define the time exactly?
Big thanks for any clarification!
EDIT: Do I need to decalre the list before passing it as a parameter in method? Above code causes errors in VS2010, saying that C2061: syntax error : identifier 'list' and IntelliSense: list is not a template even though I did #include <list>. What's wrong?

cocos2dx. how to set a callback (passing an argument) after sequence of animations

I'm trying to set an action after a sequence of animations, basically I need to use an object (that I want to pass as argument) for a method.
The only way I've found is using CCCallFunc which is not (as far as I know) supposed to have arguments.
Does exist a sort of "callBlock" of cocos2d/objective-c ? that's an awesome insturment, I would like to know if there is something similiar with cocos2d-x
here's the code:
CCCallFuncND *callBack = CCCallFuncND::create(this, callfuncND_selector(MyObject::method), data);
since I'm trying to do it within a class (not initialized) with only static functions I cannot use "this" so I tried to set it as NULL but in this case I got an error...
I had to do same thing, after running the sequence of actions: I wanted to remove sprites from the bacthNode, so that my animation frames does not appear on screen as the animation finishes so I had to pass the batch node to the function, and this is how I achieved it :-
CCSequence *seq=CCSequence::createWithTwoActions(
CCAnimate::create(animation),
CCCallFuncO::create(
animation,
callfuncO_selector(GameLayer::animationReshuffleFinished),
(CCObject*)animBatchNode)
);
function you need is CCCallFuncO instead of ND here O stands for Object.
CCCallFuncO::create(
animation,
callfuncO_selector(GameLayer::animationReshuffleFinished),
(CCObject*)animBatchNode)
where animation is my CCAnimate object
animationReshuffleFinished is the call back function of my class GameLayer which I want to be called as the animation finishes.
and (CCObject*)animBatchNode) is the argument to the function animationReshuffleFinished
and here is the definition of function
void GameLayer::animationReshuffleFinished(CCObject *sender){
CCSpriteBatchNode *animBatchNode = (CCSpriteBatchNode*) sender;
animBatchNode->cocos2d::CCNode::removeAllChildrenWithCleanup(true);
}
please let me know if this serves your purpose.
You just can not. If you check the definition of SEL_CallFuncXXX, you will found function must be a member function of CCObject.
Current cocos2d-x callback is totally copy from cocos2d but the Objective-C manner is not fit to C++. The limitations are:
1, might not work if you pass a object which has multi base class.
2, can not pass parameter which allocate on stack such as XXX::f(bool), you can not pass bool in it.
3, as you question mentioned, the callback function mush be a member function of a class which derived from CCObject. So static function or global function can not use
May be you are curious why they don't use std::function & std::bind instead, well, may be they copied cocos2d too fast and have not time to think about it.

Force error (compile time) if anyone calls a method in C++

DISCLAIMER: CCNode class is part of the cocos2d-x framework, which i didn't desing.
Base class CCNode has a init method:
virtual bool init();
My derived class needs two arguments, so I declare a new init method:
virtual bool init(int, int);
I'd like to enforce the use of the new init(int a, int) instead of the original one.
I know I have the option to call the new one with default parameters, but it doesn't feel right in the context.
I'm searching for a way to tell the user "Call init(int, int) instead" if anyone tries to call that one. I'd rather get that at compile time that at runtime.
I've tried C++11's static_assert(false, "message"), but fails without calling it...
If your really want to prevent someone calling the standard node method I think you should inherit it privately. However, the more cocosy way of doing this would simply be to call the new init from your create method, which is the only one that should be called by outside code when constructing your object anyway.
Sounds like you have source code access, since you tried sticking a static assert in there? The only way I think you can do exactly what you want is to templatize the function in question. Placing a static assert in a templatize function is a good way to ensure it doesn't compile.
Another option would be to hide the declaration in the private section of your class.
Lastly, a run-time assertion is the most common way I ever achieve what you're asking to do.
If you don't have source code access to that init function, then I really don't think you can do what you're asking.