I built an interface taking pointers to functions. Sometimes this calculation depends on state, which I want to encapsulate in a class and pass its method:
#include <iostream>
class Printer {
public:
static void print(int i) { // Want to get rid of the static
std::cout << i << "\n";
}
};
template<typename int_func>
void with_1(int_func func) {
func(1);
}
int main(int argc, char const *argv[]) {
Printer printer;
with_1(printer.print);
return 0;
}
I need non-static methods (and would even prefer overloading operator()). However removing the static results in error: a pointer to a bound function may only be used to call the function.
I could use a dummy like this:
Printer printer;
void dummy(int i) {
printer.print(i);
}
int main(int argc, char const *argv[]) {
with_1(dummy);
return 0;
}
But that does not look elegant to me. Can I write a template that accepts both, function pointers and non-static methods? Or is there even a better design pattern for my problem?
You can not simply pass non-static method like this, because they work on instance. A simply solution is to use lambda:
#include <iostream>
class Printer {
public:
static void print(int i) { // Want to get rid of the static
std::cout << i << "\n";
}
};
template<typename int_func>
void with_1(int_func func) {
func(1);
}
int main(int argc, char const *argv[]) {
Printer printer;
// Can use capture by reference because we are sure printer still
// exist during execution of with_1
with_1([&printer](int i){ printer.print(i); });
return 0;
}
example
Try this:
int main(int argc, char const *argv[]) {
Printer printer;
with_1( std::bind( &Printer::print, printer, std::placeholders::_1 ) );
return 0;
}
(You'll need to #include <functional>.)
Related
Lets consider the next piece of code:
#include <iostream>
void print()
{
std::cout << "I feel void" << std::endl;
}
void (*func)();
func = print;
This does not compile, since "func does not name a type".
But I already declared about func's type. It's a function pointer that takes no arguments and returns void. Why do I need to name a type again?
Do I always have to initialize a function pointer when declaring it?
No.
However, you cannot have expression statements such as assignments in namespace scope.
you can do that in main! , you cant do that in namespaces:
void (*func)();
void print()
{
std::cout << "I feel void" << std::endl;
}
int main(int argc, char* argv[])
{
func = print;
return 0;
}
but if you want do that before main execution , you can try below code(I prefer dont use this , but it's helpful sometimes):
#include <iostream>
void (*func)();
void print()
{
std::cout << "I feel void" << std::endl;
}
class Initilizer
{
public:
Initilizer()
{
init();
}
static void init()
{
func = ::print;
}
};
Initilizer obj;
int main(int argc, char* argv[])
{
func(); /*Test func*/
return 0;
}
I'm trying to create a class that stores pointers to member functions of other classes and that can be executed from a text command (like a game console).
I did something functional, based on an example found here, that stores members with string-like input. Below is my implementation.
file: Command.hpp
#include <string>
#include <functional>
#include <unordered_map>
#include <string>
#include <iostream>
using namespace std;
class Command
{
public:
Command();
virtual ~Command();
void RegisterCommand(string command, function<void(const string&)> fun);
void Run(const string& command, const string& arg);
private:
unordered_map<string, function<void(const string&)>> functions;
};
file: Command.cpp
Command::Command()
{
}
Command::~Command()
{
}
void Command::RegisterCommand(string command, function<void(const string&)> fun)
{
functions[command] = fun;
}
void Command::Run(const string& command, const string& arg)
{
functions[command](arg);
}
file: main.cpp
#include "Command.hpp"
// function to register
void xyz_fun(const string& commandLine)
{
cout << "console output: " << commandLine << endl;
}
int main(int argc, char* argv[])
{
Command m_Cmd;
// Register function
m_Cmd.RegisterCommand("xyz_fun", xyz_fun);
// Run registered function
m_Cmd.Run("xyz_fun", "hello world.");
return EXIT_SUCCESS;
}
My question is how to implement a generic class to store members with unknown input arguments (Booleans, integers, doubles, strings, etc.).
For example, I could do:
m_Cmd.RegisterCommand("xyz_fun2", xyz_function2);
and call
m_Cmd.Run("xyz_fun2", false)
which has a boolean argument instead of a string.
Thanks in advance for your attention and any help is welcome.
Instead of
unordered_map<string, function<void(const string&)>> functions;
you could do
union acceptable_types { int i; char c; bool b; std::string* s; ... };
unordered_map<string, function<void(acceptable_types)>> functions;
Then when calling functions, just place the value wanted by the function into a variable of type acceptable_types.
If a function is wants to use a specific value, it should just use a specific member of the acceptable_types union.
Here's an example:
#include "Command.hpp"
void
my_bool_func (acceptable_types union_param)
{
bool bool_var = union_param.b;
// ...
// Use bool_var
// ...
}
void
my_string_func (acceptable_types union_param)
{
std::string string_var = *(union_param.s);
// ...
// Use string_var
// ...
}
int
main(int argc, char* argv[])
{
Command my_command;
acceptable_types union_var;
my_command.RegisterCommand("my_bool_func", my_bool_func);
my_command.RegisterCommand("my_string_func", my_string_func);
union_var.b = true;
my_command.Run("my_bool_func", union_var);
*(union_var.s) = "hello world.";
my_command.Run("my_string_func", union_var);
return 0;
}
I have a class that has to process data from various files. I thought about creating one function that will read the specified file and then also accept a call back so that it can use that to process the line. Below is an example class to represent what I am trying to do:
#include <iostream>
#include <vector>
#include <string>
class Example
{
std::vector<std::string> m_exampleFileData {
"test1",
"test2",
"test3"
};
public:
void doSomethingMain(const std::string& path)
{
processFile(path, doSomething);
}
private:
void processFile(const std::string& filePath, void (Example::*fpProcessLine)(const std::string&) )
{
for (const auto& line : m_exampleFileData) {
this->*fpProcessLine(line);
}
}
void doSomething(const std::string& line)
{
std::cout << "Hello: " << line << '\n';
}
};
int main(int argc, char** argv) {
const std::string filePath{"path"};
Example ex;
ex.doSomethingMain(filePath);
}
Compiler explorer: https://godbolt.org/z/LKoXSZ
The main issue is that no matter what I do I can't seem to be able to pass the function properly to processFile. Is there a way to do this in C++? How do I go about this?
You need to spell things out explicitly, in this situation:
processFile(path, &Example::doSomething);
Furthermore, you also need to slap on an extra pair of parenthesis, due to operator precedence:
(this->*fpProcessLine)(line);
I am using a framework that passes around function pointers as void*. I want a mock to return a function pointer, and I want to define the function in-place (like a lambda; which does not work as shown below).
A minimal working example is shown below.
#include <gtest/gtest.h>
#include <gmock/gmock.h>
using namespace std;
using namespace testing;
class Original
{
public:
typedef int(*fptr)();
void Func()
{
void* f = Func2();
fptr func = reinterpret_cast<fptr>(f);
if (func) {
int i = func();
if (i == 1) {
//do something
} else if (i == 3) {
//NOTE my unit test should test this decision branch
}
}
}
static int Func3() {return 1;}
virtual void* Func2() {return (void*)&Func3;}
};
class MyMock : public Original
{
public:
MOCK_METHOD0(Func2, void*());
};
My main goal: I want to get rid of this function, and define it inline in the EXPECT_CALL(). See below.
int MockFunc() {cout << "mock func" << endl; return 3;}
The test case:
TEST(MYTEST, Test)
{
MyMock m;
//WORKS: compiles and works as expected,
//but I do not want to use **MockFunc**
EXPECT_CALL(m, Func2()).Times(AtLeast(1))
.WillRepeatedly(Return(&MockFunc));
//DOES NOT WORK: Does not compile, of course
//(compiler message below this code block)
EXPECT_CALL(m, Func2()).Times(AtLeast(1))
.WillRepeatedly(Return((void*)&([](){return 3;})));
m.Func();
}
main.cpp:117:90: error: taking address of temporary [-fpermissive]
For completeness, the main():
int main(int argc, char** argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
So the question again: How can I get rid of the MockFunc() function and define its contents in-place within the Return()?
The following statement should work:
EXPECT_CALL(m, Func2()).Times(AtLeast(1)).WillRepeatedly(Return((void*)(+([](){return 3;}))));
It exploits the fact that non-capturing lambdas decay to function pointers.
In other terms, the resulting type of the expression (+([](){return 3;}) is int(*)(). You can then cast it to void* as you did. The error should disappear as well, for you are no longer getting the address of a temporary.
The code should explain my difficulty. Though the code itself is quite meaningless, I'm planning to add containers in MyClass, and use algorithms with member functions.
#include <cstdlib>
#include <algorithm>
#include <functional>
using namespace std;
class MyClass
{
public:
MyClass() { a = 0; }
~MyClass() {}
private:
int a;
bool tiny_test (int);
int Func();
};
bool MyClass::tiny_test (int b)
{
return a == b;
}
int MyClass::Func()
{
// does not compile
(mem_fun(&MyClass::tiny_test))(this);
// commented below is another attempt, also no success
//mem_fun1_t<bool, MyClass, int> tmp_functor = mem_fun(&MyClass::tiny_test);
//tmp_functor(this);
return 0;
}
int main(int argc, char** argv)
{
return 0;
}
Thanks a lot! Btw, I'm not using a static member function, simply because I believe it must work for non-static member functions.
P.S. Eric, Jarod42, thanks for prompt replies!
bool MyClass::tiny_test (int b)
{ // ^^^^^ You missed this argument
return a == b;
}
Try this:
// Supply one more argument. E.g., 3
(mem_fun(&MyClass::tiny_test))(this, 3);