Passing templated class? - c++

I'm working on performing some operations on a polymorphic doubly-linked list, and I seem to be having some issues with that.
I'm trying to pass a instance of the class to this function:
void performoperator(List<string> list, string operator, int &OpCount){
//...
}
and I'm trying to call it as such:
List<string> list;
//...
performoperator(list, temp, OpCount);
The compiler doesn't appear to accept the way in which I'm calling the function, and I'm fairly certain the issue is with the templated class somehow. What am I doing improperly?
Edit: Resolved, won't let me post as a solution as I'm a new user.
The issue was the I needed to pass the list by reference.

void performoperator(List<string> list, string operator, int &OpCount)
^^^^^^^^
operator is a reserved keyword in C++; you cannot use it as a variable name.

Just a guess: You put template code in cpp file not in your header file

Related

Passing a member function of a class to a parameter outside the class

How do you pass a member function of a class as a parameter to another member function of another class?
class theSecondClass
{
public:
void theFunctionReceiver(void (theFirstClass::*Function)(void));
{
// This part is wrong. "Operand of * must be a pointer"
(*Function)();
}
}
class theFirstClass
{
public:
theSecondClass * SecondClassInstance;
void theFunctiontoPass(void)
{
printf("It worked \n");
return;
}
void theFunctiontoCall(void)
{
SecondClassInstance->theFunctionReceiver(theFunctiontoPass);
}
};
Take the assumption that theSecondClass and theFirstClass are both made already. I'm calling theFirstClass->theFunctiontoCall() from somewhere.
I don't get it. When I pass it in, isn't it pass in as a pointer?
I've taken a look at several similar threads around, but I don't understand them fully.
I'm using VS 2013, basic compiler.
When you write this statement:
SecondClassInstance->theFunctionReceiver(theFunctiontoPass);
What you presumably meant was:
SecondClassInstance->theFunctionReceiver(&theFunctiontoPass);
Which should give you a compiler warning that it's an unqualified member reference, which would point out to you that what you are actually writing is:
SecondClassInstance->theFunctionReceiver(&theFirstClass::theFunctiontoPass);
You are getting a pointer to a member function on the class definition. The "this" is not implicit or included in the package. The only way you're going to be able to call it without a class instance is if it is static. (In which case it won't type-check as a member function...it will just be an ordinary function pointer.)
If I'm going to pass in a reference to my class, why would I even need to pass it the function? Couldn't I just call it with, in the case of the link, ButtonObj->Buttonfunc();
The only reason you would use pointers to member functions is to get some kind of abstraction, where one piece of code can call a member function it doesn't need to explicitly name. If you're okay with theSecondClass::theFunctionReceiver knowing the name of theFirstClass::theFunctionToPass and the identity of theFirstClass...then sure, just pass a reference to an instance of theFirstClass and call the method explicitly.
You might want a situation where theSecondClass is going to call any one of a number of member functions on theFirstClass with matching signatures...it just doesn't want to hard-code which one. In that case, then passing a pair of a class reference and a member function can be done. You seem to suspect this doesn't come up too often as useful, and you would be right. Every year I have to go back and look up the syntax for how to call pointers-to-members on a class, because it almost never comes up except in StackOverflow questions:
How to call through a member function pointer?
More likely what you want (and what people asking those SO questions actually want) is to separate concerns so that theSecondClass has a hook to execute something, but doesn't need to know about theFirstClass at all. Look into lambdas, std::function, and std::bind for generalized solutions which you may be able to experiment with to your satisfaction.
Here is an example to show you what that would look like to conveniently wrap up the call abstractly into a std::function. It makes a function object on the spot, that captures the enclosing this pointer so that when it is invoked it calls the method on the object:
#include <iostream>
#include <functional>
class theSecondClass {
public:
void theFunctionReceiver(std::function<void()> const & Function) {
Function();
}
};
class theFirstClass {
private:
theSecondClass * SecondClassInstance;
public:
void theFunctiontoPass() {
std::cout << "It worked\n";
}
void theFirstClass::theFunctiontoCall() {
SecondClassInstance->theFunctionReceiver(
[this]() {theFunctiontoPass();}
);
}
};
int main() {
theFirstClass tfc;
tfc.theFunctiontoCall();
}
Note this is C++11, which I suggest using if you're not already. Less convenient notations and mechanisms exist in C++98, though.
This corrects problems with your code that go beyond the issue you mention. Please review writing a Minimal, Complete, Verifiable Example. It should be possible to paste your provided code into a compiler and see only the error you wish to discuss.
This adds semicolons after the ends of class definitions
This removes the semicolon after method declarations when you are supplying bodies in the class
You needed various forward definitions to get it to work as you had it, this doesn't require them
When a function takes no parameters, it's customary to define as void foo() not void foo(void). return; as the last line of a function returning no value is kind of superfluous as well.
Avoid writing new C++ code using printf, learn iostreams
Bias member variables to being private or protected.
On StackOverflow code samples try and keep them short and not need scroll bars; it's best to not give opening braces their own line (most of the time)
While naming is subjective, I'd suggest that giving your class names initial caps is a better idea than giving variables initial caps.

Vector of void function pointers with parameters C++

I'm creating an application with a class that has a number of animation methods. I need these animation methods to be called in a random way. So, my idea was to create a vector of void function pointers, and iterate through the vector. I can't get it to compile though. I'm getting the error: "invalid use of void expression".
Applicable code:
.h
std::vector<void(*)(int,float)> animationsVector;
void setAnimations();
void circleAnimation01(int circleGroup, float time);
.cpp
polygonCluster01::polygonCluster01()
{
setAnimations();
}
void polygonCluster01::setAnimations()
{
animationsVector.push_back(circleAnimation01(1,2.0)); //error is here
}
void polygonCluster01::circleAnimation01(int circleGroup, float animLength)
{
//other code
}
I've followed some other posts here which suggest I'm doing it right, but it still won't compile, and I'm not sure why.
polygonCluster01::circleAnimation01 is not a free-standing function, but a member function. Thus, you need a member function pointer to store its adress. Here is the type you're looking for :
std::vector<void(polygonCluster01::*)(int,float)> animationsVector;
// ^^^^^^^^^^^^^^^^^^
Edit: let's complete this answer.
When you give the correct type to your vector, it still won't compile. This is because, as stated by crashmstr, function pointers and member function pointers are just that - a pointer to a (member) function. In particular, they can't store parameters for later use, which you are trying to do.
So what you actually need is not a mere (member) function pointer, but something that can wrap a function and some parameters to call it later.
Well, C++11 has you covered ! Take a look at std::function. It's a type-erased container, designed to do just what is written above. You can use it like this :
std::vector<std::function<void(polygonCluster01*)>> animationsVector;
...
animationsVector.push_back(std::bind(
&polygonCluster01::circleAnimation01, // Grab the member function pointer
std::placeholders::_1, // Don't give a caller for now
1, 2.0 // Here are the arguments for the later call
));
...
animationsVector[0](this); // Call the function upon ourselves
Your vector contains function pointers, not the result of the function you are calling in there.
animationsVector.push_back(circleAnimation01(1,2.0));
Use this instead
animationsVector.push_back(circleAnimation01);
The invalid use of void expression that you are getting is because you are trying to store the result of the circleAnimation01 function call which is void instead of a pointer to a function that returns void upon receiving an int and a float.
Also, as Quentin has stated, you need them to be functions, not member functions, either change the signature of the vector or change those members to free functions.

How to I search for the definition of a function without a name

I was trying to understand a cpp program when I encounter this:
has_image =(*kinfu_) (depth_device_).
I am trying to understand what the function does, but without any name I am unable to search for the function definition.
Do you guys have any suggestion on how I should go about searching of it's definition?
Thanks
kinfu_ is likely a function pointer whose whole purpose is that it doesn't have a single possible value, but multiple ones. You need to find the place where its value was set, and that will lead you to the concrete function being executed.
You can also use a debugger to print the value of kinfu_, which will also print out the name of its current function value.
kinfu_ could also be a pointer to an instance of a class that defines operator(), in which case you need to find the definition of the member.
Search the code for kinfu_. It's probably a data member of the class. My guess is that kinfu_ is a pointer to a functor, e.g.:
struct SomeFunctor {
bool operator()(float depth) { … }
};
⋮
class SomeClass {
⋮
private:
SomeFunctor * kinfu_;
⋮
};

How to use a non-static member function in Hasher?

I need to establish a hash table using a hasher different from the default one, so I write something like:
class foo {
public:
...
private:
struct myhasher {
size_t operator() (myclass bar) { return hash_calculation bar; }
}
static size_t hash_calculation (myclass bar) {
// do some calculation
}
hash_map<myclass, myhasher> myhashmap;
}
It works. Now for some reason I have to write a non-static member function to replace hash_calculation, say, it needs a non-static member of the class as an argument. Then the whole thing failed because I cannot use a non-static method in a nested struct.
This is somehow similar to another widely discussed problem: how to use a non-static function to do comparison or sorting. See for example:
Using a non-static class member inside a comparison function
and
C++ std list sort with custom comparator that depends on an member variable for the object instance . They both established a functor instead of a function as the comparator. However in my case this trick does not work because I need a class name inside the hash_map definition, not a specific struct object. What should I do? Thanks in advance for your help!
You can't. How is the hash_map supposed to know which instance of myhasher should be used when calling myhaser::hash_calculation?
hash_map isn't part of the standard C++ library, not even in C++11, so it's a custom class, and you have included no information about how it works. If there is a way for it to take some sort of constructor argument for which myhasher it should use, you're in luck. But it doesn't sound like it.
Also, you're using pass by value when you probably mean to pass in a const reference. Passing by value is likely going to be really slow and inefficient.
The standard "hash-map", i.e., std::unordered_map<K, V, H, E, A> takes a hash object of type H as constructor argument. A copy of this object is used to determine the hash for the object by way of the function call operator. This way can provide some context. Obviously, you were already using a non-static function call operator but you choose to delegate to a static member.

`this` operator in c++?

Sorry not sure if this has been asked before, I really dont know what to look up either. I'm new to C++ from Java. When we want to call a function on an object in Java, we say picture.rotateRight();
Then, in rotateRight(), we'd have something like int height=this.getHeight();. However, how do we do this in C++? I have a method named invertcolors(); and then I have something like:
Image* myImage = new Image();
bool b = myImage->ReadFromFile("in_01.bmp");
myImage->invertcolors();
void invertcolors(){
int width=TellWidth();
int height=TellHeight();
...
}
How do I access myImage from the method definition without actually saying myImage (since that name can later be changed).
Also, the function parameters are non-negotiable.
First of all, your invertcolors() function definition is a non-member function. Although you've declared it inside the Image class, you haven't linked the implementation to the class in any way so the compiler thinks its a non-member function. To make it a member of Image, you need to use Image::invertcolors like this:
void Image::invertcolors(){
int width=TellWidth();
int height=TellHeight();
...
}
You do get this in C++, but it's a pointer so you have to use this->getHeight() in C++. However, note that it is redundant in this case. As a beginner you'll probably find the only real use in a method having the same argument name as an attribute. In this case, you'll need to use this->height = height for example. However, note that C++ has a nice syntax addition here. This code does the same as a simple setter:
void Image::setHeight(int height): height(height) {}
Note that neither in Java nor C++ is this an operator. ., -> and + are examples of operators.
this is a keyword, not an operator, and it does exist in C++. It's a pointer, so you'll use it with ->, not ., when accessing members.
Inside a member function, this->whatever is implicit, so you can just use whatever on its own, and the compiler will figure out that you mean this->whatever. There are a few cases (mostly in templates) that it can make sense to use this-> in C++ as well, but it's only rarely necessary (I'm aware of the times, but after writing C++ for a couple of decades, I can probably still count the times I've done it on my fingers).
If your code is not in a member function, then it has to explicitly refer to some particular object (much as in Java).
"this" is also available in C++. It's a pointer to the object on which the function is being called.
Assuming that invertcolors(), TellWidth(), and TellHeight() are member functions of the Image class, it will work just as you've written it.
In C++, this is a const-pointer to the object on which the method was invoked (as opposed to Java, where this is a reference). So, rather than:
this.doSomething(); // in Java
you'd say:
this->doSomething(); // in C++.
EDIT: Sorry, didn't see the part about the parameters. New Answer: If the function parameters are non-negotiable, and you can't be arsed to define invertColors as a member function for Image (by extending the Image class) then you'll need a globally defined variable.
Outside of your main function, declare Image* myimg;
then use myimg like normal inside your function.
ex:
Image* myImg;
int main()
{
..all your initialization, etc.
invertColors();
}
void invertColors()
{
int width = myImg->width;
...
}
Reading the comments, are you missing how to define the method:
Header file: Image.h
class Image : public BMP {
public:
void invertcolors();
};
Source file Image.cpp
void Image::invertcolors()
{
int width=TellWidth();
int height=TellHeight();
// ...
}