call a function N times by write N parentheses after the function - c++

I want to implement the following:
I define a function. And when I write N ()'s after the function, the function will be called N times.
I give an example:
#include <iostream>
using namespace std;
typedef void* (*c)();
typedef c (*b)();
typedef b (*a)();
a aaa()
{
cout<<"Google"<<endl;
return (a)aaa;
}
int main()
{
aaa()()()();
system("pause");
}
Then the output is :
Are there any other methods to implement that?

It's simple using functors.
#include <iostream>
struct Function
{
Function& operator()() {
std::cout << "Google" << std::endl;
return *this;
}
};
int main()
{
Function f;
f()()()();
}

You might be interested in functors:
#include <iostream>
class my_functor {
public:
// if called without parameters
my_functor& operator()(){
std::cout << "print" << std::endl;
return *this;
}
// if called with int parameter
my_functor& operator()(int number){
std::cout << number << std::endl;
return *this;
}
};
int main(){
my_functor functor;
functor()(5)();
return 0;
}
By overloading the function call operator () you can add function-behaviour to your object. You can also define different parameters which shall be passed to your overloaded ()-operator and the respective function call will be invoked. Just make sure that you return a reference to this-instance, if you want to invoke the function call on the object instance, that was modified by the previous function call.

Related

Functions that cannot be overloaded in C++

Member function declarations with the same name and the name parameter-type-list cannot be overloaded if any of them is a static member function declaration. For example, following program fails in compilation.
#include<iostream>
class Test {
static void fun(int i) {}
void fun(int i) {}
};
int main()
{
Test t;
getchar();
return 0;
}
I don't understand why the following example can run:
#include<iostream>
class Test {
public:
static void fun(double i) {
std::cout << i << "\n";
}
void fun(int i) {
std::cout << i;
}
};
int main()
{
Test t;
t.fun(5.5);
t.fun(4);
return 0;
}
The second Example will run because the parameter types are different in both the function, i.e. double in the first and int in second. So function overloading takes place
Function overloading only works when you have different set of parameters, in the example's case it's int and double. change the parameter data type.

Call a C-style function address with std::bind and std::function.target using a method from object

I have a C-style function, which stores another function as an argument. I also have an object, which stores a method that must be passed to the aforementioned function. I built an example, to simulate the desired situation:
#include <functional>
#include <iostream>
void foo(void(*f)(int)) {
f(2);
}
class TestClass {
public:
std::function<void(int)> f;
void foo(int i) {
std::cout << i << "\n";
}
};
int main() {
TestClass t;
t.f = std::bind(&TestClass::foo, &t, std::placeholders::_1);
foo( t.f.target<void(int)>() );
return 0;
}
What is expected is that it will be shown on screen "2". But I'm having trouble compiling the code, getting the following message on the compiler:
error: const_cast to 'void *(*)(int)', which is not a reference, pointer-to-object, or pointer-to-data-member
return const_cast<_Functor*>(__func);
As I understand the use of "target", it should return a pointer in the format void () (int), related to the desired function through std :: bind. Why didn't the compiler understand it that way, and if it is not possible to use "target" to apply what I want, what would be the alternatives? I don't necessarily need to use std :: function, but I do need the method to be non-static.
This is a dirty little hack but should work
void foo(void(*f)(int)) {
f(2);
}
class TestClass {
public:
void foo(int i) {
std::cout << i << "\n";
}
};
static TestClass* global_variable_hack = nullptr;
void hacky_function(int x) {
global_variable_hack->foo(x);
}
int main() {
TestClass t;
global_variable_hack = &t;
foo(hacky_function);
return 0;
}
//can also be done with a lambda without the global stuff
int main() {
static TestClass t;
auto func = [](int x) {
t->foo(x); //does not need to be captured as it is static
};
foo(func); //non-capturing lambas are implicitly convertible to free functions
}

How to define a lambda function inside a struct in c++

is there any possibility to have a lambda expression inside a struct in c++ . logic goes as follows.
struct alpha {
<lambda function> {
/* to do */
}
};
int main()
{
int a = //call the function inside the struct and compute.
}
You'll need to use std::function:
#include <iostream>
#include <functional>
struct Foo
{
const std::function<void()> hello = [] () { std::cout << "hello world!" << std::endl; };
};
int main()
{
Foo foo {};
foo.hello();
}
See live on Coliru.
It's unclear what you're asking exactly.
But a lambda, a.k.a. a functor, in C++ is mainly syntactic sugar for operator().
If you want to have a "callable" struct, you can just define operator() like this:
struct alpha {
int operator() () {
return 42;
}
};
int main()
{
alpha x;
int a = x();
std::cout << a << std::endl; // prints "42"
}
Yes, you can use std :: function to declare a pointer to a function, and when initializing the structure, substitute a function with the lambda pointer, for example
struct alpha{
std::function<int(int)>
};
...
alpha a{[](int a){return a;}};

C++ function with function parameter more elegant

I have the following code:
#include <iostream>
using namespace std;
class A
{
int m_value;
public:
A(int value)
{
m_value = value;
funcA(&A::param);
}
void funcA(void (A::*function)(int))
{
(this->*function)(m_value);
}
void param(int i)
{
cout << "i = " << i << endl;
}
};
int main()
{
A ob(10);
return 0;
}
I have a class in which I call a function that receives another function as parameter. The function call is at line funcA(&A::param). What I want is to be able to pass a function as parameter without being necessary to specify the class scope: funcA(&param). Also I didn't want to use typedefs that's why I have the code a little 'dirty'.
Is there any possibility to achieve this?
This cannot be done. A function pointer in a class must be identified using the class scope (A::function)
That is kind of ugly.
The first thing you should look at doing is recoding things to use inheritence and dynamic dispatch instead. To do this you change the A class to have a virtual method that funcA calls
class A {
...
void funcA () {
custom_function(m_value);
}
protected:
virtual void custom_function (int)=0;
}
Now for every different custom_function you want to use, you declare a new class derived from A, and implement the function in there. It will automagically get called from funcA:
class A_print : public A {
public:
virtual void custom_function (int param) {
std::cout << "param was " << param << std::endl;
}
}
If that isn't flexible enough for you, the next best C++-ish solution would be to implement a functor (an object that acts as a function, possibly even overriding the ()operator.
I don't understand why you can't just do this:
#include <iostream>
using namespace std;
class A
{
int m_value;
public:
A(int value)
{
param(value);
}
void param(int i)
{
cout << "i = " << i << endl;
}
};
int main()
{
A ob(10);
return 0;
}

How to get Windows thread pool to call class member function?

I want the Windows thread pool (QueueUserWorkItem()) to call my class' member functions.
Unfortunately this cannot be done directly by passing a member function pointer as an argument to QueueUserWorkItem().
What makes it difficult is that more than one member function must be callable and they have different signatures (all return void though).
One probably need to add a few layers of abstraction to get this to work, but I'm not sure how to approach this. Any ideas?
This might help.
You can use tr1::function () and tr1::bind to "coalesce" various calls:
#include <iostream>
#include <tr1/functional>
using namespace std;
using namespace tr1;
class A
{
public:
void function(int i) { cout << "Called A::function with i=" << i << endl; }
};
void different_function(double c) {
cout << "Called different_function with c=" << c << endl;
}
int main(int argc, char* argv[])
{
function<void()> f = bind(different_function, 3.14165);
f();
A a;
f = bind(&A::function, a, 10);
f();
return 0;
}
The address of the function object can be passed as a single callable object (needing only one address).
Example:
In your class add:
char m_FuncToCall;
static DWORD __stdcall myclass::ThreadStartRoutine(LPVOID myclassref)
{
myclass* _val = (myclass*)myclassref;
switch(m_FuncToCall)
{
case 0:
_val->StartMyOperation();
break;
}
return 0;
}
Make a member for adding to queue then
void myclass::AddToQueue(char funcId)
{
m_FuncToCall=funcId;
QueueUserWorkItem(ThreadStartRoutine,this,WT_EXECUTEDEFAULT);
}
or create
typedef void (*MY_FUNC)(void);
typedef struct _ARGUMENT_TO_PASS
{
myclass* classref;
MY_FUNC func;
}ARGUMENT_TO_PASS;
and then
void myclass::AddToQueue(MY_FUNC func)
{
ARGUMENT_TO_PASS _arg;
_arg.func = func;
_arg.classref = this;
QueueUserWorkItem(ThreadStartRoutine,&_arg,WT_EXECUTEDEFAULT);
}
If you need further explanation feel free to ask :)
EDIT: You'll need to change the ThreadStartRoutine for the second example
and you can also change the struct to hold the passing argument