Is it possible to create a vector that has functions pushed back?
I've tried doing something with pointers, but it only works with functions without parameters.
For example,
#include <iostream>
#include <vector>
using namespace std;
void printInt();
int main()
{
vector<void (*)()> functionStack;
functionStack.push_back(printInt);
(*functionStack[0])();
}
void printInt()
{
cout << "function works!" << 123 << endl;
}
That works, but not what I need.
The correct version of that would be a function that has parameters: void printInt(int a) and you could call it with different values like 4 or -1 but from the vector functionStack.
It's probably more complex if the functions in the vector are with different parameters, so let's assume that every function has the same type and amount of parameters.
This:
void (*)()
is a function pointer taking no arguments. So change it to take the desired argument.
void (*)(int)
Like so:
void printInt(int x)
{
cout << "function works!" << x << endl;
}
int main()
{
vector<void (*)(int)> functionStack;
functionStack.push_back(printInt);
(*functionStack[0])(123);
}
You are correct in saying the functions must have the same type and number of parameters for this to be valid.
You basically had it already.
#include <iostream>
#include <vector>
using namespace std;
void printInt(int a);
int main()
{
// Just needed the parameter type
vector<void (*)(int)> functionStack;
// Note that I removed the () from after the function
// This is how we get the function pointer; the () attempts to
// invoke the function
functionStack.push_back(printInt);
(*functionStack[0])(42);
}
void printInt(int a)
{
cout << "function works! " << a << endl;
}
This is also a situation where std::function might be beneficial as well.
#include <iostream>
#include <functional>
#include <vector>
using namespace std;
void printInt(int a);
int main()
{
// Similar syntax, std::function allows more flexibility at a
// lines of assembly generated cost. But it's an up-front cost
vector<std::function<void(int)>> functionStack;
functionStack.push_back(printInt);
// I don't have to de-reference a pointer anymore
functionStack[0](42);
}
void printInt(int a)
{
cout << "function works! " << a << endl;
}
Related
I have the following code:
#include<iostream>
using namespace std;
void saludo();
void despedida();
int main(){
void (*Ptr_Funciones[2])() = {saludo, despedida};
(Ptr_Funciones[0])();
(Ptr_Funciones[1])();
return 0;
}
void saludo(){
cout<<"\nHola mundo";
}
void despedida(){
cout<<"\nAdios mundo"<<endl<<endl;
}
Based on this, a few questions were generated which I investigated before asking but did not fully understand.
The questions are:
How do I make an array of functions, if they are of a different type?
I know that in C ++ this notation is used for undetermined parameters: (type var ...) The
thing is, I don't know how to interact with them inside the function.
If questions 1 and 2 are possible, can these points be combined when creating function
arrays?
I really have investigated. But I can't find much information, and the little I did find I didn't understand very well. I hope you can collaborate with me.
Thank you very much.
How do I make an array of functions, if they are of a different type?
You can, but you don't want to. It doesn't make semantic sense. An array is a collection of the same kind of thing. If you find that you need to make a collection of different kinds of things, there are several data structures at your disposal.
I know that in C++ this notation is used for undetermined parameters: (type var ...) The thing is, I don't know how to interact with them inside the function.
Here's how you can use the syntax you mention. They're called variadic functions.
If questions 1 and 2 are possible, can these points be combined when creating function arrays?
Erm, I can't imagine why/when a combination of these two would be needed, but out of intellectual curiosity, awayyy we go...
A modified version of the code from the reference link above that kinda does what you want (i've used a map instead of an array, cuz why not):
#include <iostream>
#include <cstdarg>
#include <unordered_map>
template<typename T>
using fooptr = void (*) (T *t...);
struct A {
const char *fmt;
A(const char *s) :fmt{s} {}
};
struct B : public A {
B(const char *s) : A{s} {}
};
void simple_printf(A *a...)
{
va_list args;
auto fmt = a->fmt;
va_start(args, a);
while (*fmt != '\0') {
if (*fmt == 'd') {
int i = va_arg(args, int);
std::cout << i << '\n';
} else if (*fmt == 'c') {
// note automatic conversion to integral type
int c = va_arg(args, int);
std::cout << static_cast<char>(c) << '\n';
} else if (*fmt == 'f') {
double d = va_arg(args, double);
std::cout << d << '\n';
}
++fmt;
}
va_end(args);
}
int main()
{
A a{"dcff"};
B b{"dcfff"};
std::unordered_map<size_t, fooptr<struct A>> index;
index[1] = simple_printf;
index[5] = simple_printf;
index[1](&a, 3, 'a', 1.999, 42.5);
index[5](&b, 4, 'b', 2.999, 52.5, 100.5);
}
This still really doesn't do what you wanted (i.e., give us the ability to choose from different functions during runtime). Bonus points if you understand why that's the case and/or how to fix it to do what you want.
Use a type alias to make things readable:
Live On Coliru
using Signature = void();
Signature* Ptr_Funciones[] = { saludo, despedida };
Prints
Hola mundo
Adios mundo
More flexible:
You can also use a vector:
Live On Coliru
#include <iostream>
#include <vector>
using namespace std;
void saludo() { cout << "\nHola mundo"; }
void despedida() { cout << "\nAdios mundo" << endl << endl; }
int main() {
vector Ptr_Funciones = { saludo, despedida };
Ptr_Funciones.front()();
Ptr_Funciones.back()();
}
Prints the same.
More Flexibility: Calleables of Different Types
To bind different types of functions, type-erasure should be used. std::function helps:
Live On Coliru
#include <iostream>
#include <functional>
#include <vector>
using namespace std;
void saludo(int value) { cout << "\nHola mundo (" << value << ")"; }
std::string despedida() { cout << "\nAdios mundo" << endl << endl; return "done"; }
int main() {
vector<function<void()>>
Ptr_Funciones {
bind(saludo, 42),
despedida
};
Ptr_Funciones.front()();
Ptr_Funciones.back()();
}
Prints
Hola mundo (42)
Adios mundo
Here is one solution that is possible, whether it fits your needs I'm not sure.
#include <Windows.h>
#include <iostream>
void saludo()
{
std::cout << "\nHola mundo" << std::endl;;
}
void despedida()
{
std::cout << "\nAdios mundo" << std::endl;
}
void* fnPtrs[2];
typedef void* (VoidFunc)();
int main()
{
fnPtrs[0] = saludo;
fnPtrs[1] = despedida;
((VoidFunc*)fnPtrs[0])();
((VoidFunc*)fnPtrs[1])();
std::getchar();
return 0;
}
I'm looking for a way to store function pointers in a container like a vector. This is possible if all the functions have the same parameters but can I do if the functions have individually unique parameters?
#include <iostream>
#include <vector>
using namespace std;
void sayHi() {
cout << "Hi" << endl;
}
void sayNum(int num) {
cout << num << endl;
}
int main() {
vector<void(*)()> funcs; // vector of 0 argument functions
funcs.push_back(sayHi);
funcs.push_back(sayNum); // can't store sayNum because it takes arguments
}
Note that I can't use std::function or std::bind because VS2013 doesn't have them and I'd rather not use the boost library. The solution must be allow the possibility to iterate through the vector of function pointers and execute each one with some valid arguments.
Forgive my potential ignorance about how function pointers work, I'm very used to doing this sort of thing in Javascript in one statement :P
Made the mistake of not including as I couldn't see it mentioned in anybody's code examples but it's probably just me being bad at C++.
Not going to accept my own answer, but thought I'd post my code just in the interests of anybody who might find it useful.
#include <iostream>
#include <vector>
#include <functional>
using namespace std;
typedef std::vector<std::function<void(void)>> f_list;
f_list f1;
void _sayHi();
void _sayNum(int num);
void sayHi() {
f1.push_back(
std::bind(&_sayHi)
);
}
void sayNum(int num) {
f1.push_back(
std::bind(&_sayNum, num)
);
}
void _sayHi() {
cout << "hi" << endl;
}
void _sayNum(int num) {
cout << num << endl;
}
int main() {
sayHi();
sayNum(5);
for (int i = 0; i < f1.size(); i++) {
f1.at(i)(); // will execute desired functions
}
}
VS 2103 has std::function, std::bind and lambdas. Simply use them.
This may be a really easy question but... here it goes. (Thanks in advance!)
I am simplifying the code so it is understandable. I want to use a variable calculated inside another class without running everything again.
source.ccp
#include <iostream>
#include "begin.h"
#include "calculation.h"
using namespace std;
int main()
{
beginclass BEGINOBJECT;
BEGINOBJECT.collectdata();
cout << "class " << BEGINOBJECT.test;
calculationclass SHOWRESULT;
SHOWRESULT.multiply();
system("pause");
exit(1);
}
begin.h
#include <iostream>
using namespace std;
#ifndef BEGIN_H
#define BEGIN_H
class beginclass
{
public:
void collectdata();
int test;
};
#endif
begin.cpp
#include <iostream>
#include "begin.h"
void beginclass::collectdata()
{
test = 6;
}
calculation.h
#include <iostream>
#include "begin.h"
#ifndef CALCULATION_H
#define CALCULATION_H
class calculationclass
{
public:
void multiply();
};
#endif
calculation.cpp
#include <iostream>
#include "begin.h"
#include "calculation.h"
void calculationclass::multiply()
{
beginclass BEGINOBJECT;
// BEGINOBJECT.collectdata(); // If I uncomment this it works...
int abc = BEGINOBJECT.test * 2;
cout << "\n" << abc << endl;
}
Simply define member function multiply as
void calculationclass::multiply( const beginclass &BEGINOBJECT ) const
{
int abc = BEGINOBJECT.test * 2;
cout << "\n" << abc << endl;
}
And call it as
int main()
{
beginclass BEGINOBJECT;
BEGINOBJECT.collectdata();
cout << "class " << BEGINOBJECT.test;
calculationclass SHOWRESULT;
SHOWRESULT.multiply( BEGINOBJECT );
system("pause");
exit(1);
}
In your code beginclass has no explicit constructor, hence the implicitly defined default constructor will be used, which default constructs all members. Hence, after construction beginclass::test is either 0 or uninitiliased.
What you appear to be wanting is to avoid to call beginclass::collectdata() more than once. For this you would want to set a flag that remembers if beginclass::collectdata() has been called. The member function which returns the data then first checks this flags and, if the flag was not set, calls beginclass::collectdata() first. See also the answer by CashCow.
It looks like you are looking for some kind of lazy evaluation / caching technique whereby a value is calculated the first time it is requested then stored to return it subsequently without having to reevaluate.
In a multi-threaded environment the way to achieve this (using the new standard thread library) is by using std::call_once
If you are in a single-threaded environment, and you just want to get a value out of a class, use a getter for that value. If it isn't calculated in a "lazy" fashion, i.e. the class calculates it instantly, you can put that logic in the class's constructor.
For a "calc_once" example:
class calculation_class
{
std::once_flag flag;
double value;
void do_multiply();
double multiply();
public:
double multiply()
{
std::call_once( flag, do_multiply, this );
return value;
}
};
If you want multiply to be const, you'll need to make do_multiply also const and value and flag mutable.
I'm working on a homework assignment for my C++ class and have ran across a problem that I cannot figure out what I am doing wrong.
Just to note, the separation of the files is necessary and I realize this would be much easier if I just made a structure AttackStyles inside the main and forgo the additional class file altogether.
The base of my problem is that I cannot seem to be able to loop through an array of classes and pull out base data. Here is the code:
// AttackStyles.h
#ifndef ATTACKSTYLES_H
#define ATTACKSTYLES_H
#include <iostream>
#include <string>
using namespace std;
class AttackStyles
{
private:
int styleId;
string styleName;
public:
// Constructors
AttackStyles(); // default
AttackStyles(int, string);
// Destructor
~AttackStyles();
// Mutators
void setStyleId(int);
void setStyleName(string);
// Accessors
int getStyleId();
string getStyleName();
// Functions
};
#endif
/////////////////////////////////////////////////////////
// AttackStyles.cpp
#include <iostream>
#include <string>
#include "AttackStyles.h"
using namespace std;
// Default Constructor
AttackStyles::AttackStyles()
{}
// Overloaded Constructor
AttackStyles::AttackStyles(int i, string n)
{
setStyleId(i);
setStyleName(n);
}
// Destructor
AttackStyles::~AttackStyles()
{}
// Mutator
void AttackStyles::setStyleId(int i)
{
styleId = i;
}
void AttackStyles::setStyleName(string n)
{
styleName = n;
}
// Accessors
int AttackStyles::getStyleId()
{
return styleId;
}
string AttackStyles::getStyleName()
{
return styleName;
}
//////////////////////////////////////////////
// main.cpp
#include <cstdlib>
#include <iostream>
#include <string>
#include "attackStyles.h"
using namespace std;
int main()
{
const int STYLE_COUNT = 3;
AttackStyles asa[STYLE_COUNT] = {AttackStyles(1, "First"),
AttackStyles(2, "Second"),
AttackStyles(3, "Third")};
// Pointer for the array
AttackStyles *ptrAsa = asa;
for (int i = 0; i <= 2; i++)
{
cout << "Style Id:\t" << ptrAsa->getStyleId << endl;
cout << "Style Name:\t" << ptrAsa->getStyleName << endl;
ptrAsa++;
}
system("PAUSE");
return EXIT_SUCCESS;
}
My question is why do I get the error:
"a pointer to a bound function may only be used to call the function"
on both ptrAsa->getStyleId and ptrAsa->getStyleName?
I cannot figure out what is wrong with this!
You are missing () around the function calls. It should be ptrAsa->getStyleId().
You are missing parenthesis on both calls, it should be
ptrAsa->getStyleId()
to call the function.
ptrAsa->getStyleId
is used to refer to a member value / attribute.
You need to invoke the function, not merely reference it:
std::cout << "Style Id:\t" << ptrAsa->getStyleId() << "\n";
std::cout << "Style Name:\t" << ptrAsa->getStyleName() << "\n";
You are Forgot to put () in last in Your Function(ptrAsa->getStyleId ) Calling with arrow operator.
#include <boost/bind.hpp>
#include <iostream>
using namespace std;
using boost::bind;
class A {
public:
void print(string &s) {
cout << s.c_str() << endl;
}
};
typedef void (*callback)();
class B {
public:
void set_callback(callback cb) {
m_cb = cb;
}
void do_callback() {
m_cb();
}
private:
callback m_cb;
};
void main() {
A a;
B b;
string s("message");
b.set_callback(bind(A::print, &a, s));
b.do_callback();
}
So what I'm trying to do is to have the print method of A stream "message" to cout when b's callback is activated. I'm getting an unexpected number of arguments error from msvc10. I'm sure this is super noob basic and I'm sorry in advance.
replace typedef void (*callback)(); with typedef boost::function<void()> callback;
A bound function doesn't produce an ordinary function, so you cannot just store it in a regular function pointer. However, boost::function is able to handle anything as long as it is callable with the correct signature, so that's what you want. It will work with a function pointer, or a functor created with bind.
After a few corrections to your code, I came up with this:
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <iostream>
// i prefer explicit namespaces, but that's a matter of preference
class A {
public:
// prefer const refs to regular refs unless you need to modify the argument!
void print(const std::string &s) {
// no need for .c_str() here, cout knows how to output a std::string just fine :-)
std::cout << s << std::endl;
}
};
// holds any arity 0 callable "thing" which returns void
typedef boost::function<void()> callback;
class B {
public:
void set_callback(callback cb) {
m_cb = cb;
}
void do_callback() {
m_cb();
}
private:
callback m_cb;
};
void regular_function() {
std::cout << "regular!" << std::endl;
}
// the return type for main is int, never anything else
// however, in c++, you may omit the "return 0;" from main (and only main)
// which will have the same effect as if you had a "return 0;" as the last line
// of main
int main() {
A a;
B b;
std::string s("message");
// you forget the "&" here before A::print!
b.set_callback(boost::bind(&A::print, &a, s));
b.do_callback();
// this will work for regular function pointers too, yay!
b.set_callback(regular_function);
b.do_callback();
}