Let define a structure parser :
struct parser {
int (*buffer_push_strategy)();
int (*escape_buffer_push_strategy)();
int (*do_callback_strategy)();
};
I have an initialization function :
int parser_init() {
if (some_condition) {
parser->buffer_push_strategy = buffer_push_strategy1;
parser->escape_buffer_push_strategy = escape_buffer_push_strategy1;
parser->do_callback_strategy = do_callback_strategy1;
}
else {
parser->buffer_push_strategy = buffer_push_strategy2;
parser->escape_buffer_push_strategy = escape_buffer_push_strategy2;
parser->do_callback_strategy = do_callback_strategy2;
}
return 0;
}
where the strategy functions are defined somewhere.
Ok, so my interest is to determine which strategy has been used when I write the unit tests. Any idea how to accomplish that?
I saw something on internet about is_pointer function from C++ 11, but I don`t think this would help me.
parser is a variable:
struct parserT {
int (*buffer_push_strategy)();
int (*escape_buffer_push_strategy)();
int (*do_callback_strategy)();
} parser;
If you want to know which the strategy is, you could use:
int strategy= (parser->buffer_push_strategy == buffer_push_strategy1) ? 1 : 2;
Perhaps, you prefer to store the strategy number:
int parser_init() {
if (some_condition) {
parser->buffer_push_strategy = buffer_push_strategy1;
parser->escape_buffer_push_strategy = escape_buffer_push_strategy1;
parser->do_callback_strategy = do_callback_strategy1;
return 1;
}
else {
parser->buffer_push_strategy = buffer_push_strategy2;
parser->escape_buffer_push_strategy = escape_buffer_push_strategy2;
parser->do_callback_strategy = do_callback_strategy2;
return 2;
}
}
Then, you could init the parser as:
const int STRATEGY= parser_init();
You can compare function pointers
if(p.buffer_push_strategy == buffer_push_strategy1)
See https://ideone.com/QQzL1c
Related
suppose I want to assign a const variable based on complex calculations which depend on a conditional.
if the situation were simple, I could do:
const int N = myBool ? 1 : 2;
but it's more like
const int N = myBool ? <lengthy calculation> : <other lengthy calculation>;
What I'm doing is this, but I'd like something cleaner:
int N_nonconst;
if (myBool) {
N_nonconst = <lengthy calculation>;
}
else {
N_nonconst = <other lengthy calculation>;
}
const int N = N_nonconst;
obviously, I could also do this:
int possibility1 = <lengthy calculation>;
int possibility2 = <other lengthy calculation>;
const in N = myBool ? possibility1 : possibility2;
but I'd like to actually perform only one of those lengthy calculations.
If I were extending the language, I'd consider making something like a const_deferredAssignment declaration:
const_deferredAssignment int N;
if (myBool) {
N = <...>;
}
else {
N = <...>;
}
I could also wrap those calculations up in functions/methods, but they use a bunch of locals, so it would be a fairly verbose function call.
You could wrap each calculation in a lambda, and capture the local variables to reduce the verbosity of their arguments
{
// ...
auto firstFunc = [&]() -> int { ... };
auto secondFunc = [&]() -> int { ... };
const int N = myBool ? firstFunc() : secondFunc();
}
In this way only one of the two functions are actually executed.
You could move the lengthy calculations to a separate function:
int lengthCalculation()
{
if(myBool)
{
return <lengthy calculation>;
}
else
{
return <other lengthy calculation>;
}
}
const int N = lengthCalculation();
If you don't want to create a separate function that you can use a local lambda:
const int N = [&]()
{
if(myBool)
{
return <lengthy calculation>;
}
else
{
return <other lengthy calculation>;
}
}();
you could try and use
SWITCH(myBool)
{
Case 0 : first_lengthy_calculation
Break;
Case 1 : second_lengthy_calculation
Break;
}
First off, apologies as this title probably made some of you c++ guys throw up in your mouth a little bit. However, let me explain what I'm trying to accomplish.
I'm passing a lambda (call it funcA) as a parameter to another function (call it funcB). Is there a way for me to declare variables within funcB and access them within the scope of funcA without passing them to funcA as parameters, similar to how javascript closures work?
A simple example (which fails obviously) would be as follows:
void funcB(std::function<void()> funcA) {
int testInt = 44;
funcA();
}
int main() {
funcB([&]() {
std::cout << testInt; // undefined identifier
});
return 0;
}
Well in this particular example the idiomatic way would be to use the return value:
void funcB(std::function<int()> funcA) {
int testInt = funcA();
}
int main() {
funcB([&]() {
int testInt = 44;
std::cout >> testInt;
return testInt;
});
return 0;
}
Output parameter can be used but less usual:
void funcB(std::function<void(int&)> funcA) {
int testInt = 44;
funcA(testInt);
}
int main() {
funcB([&](int& testInt) {
std::cout >> testInt;
});
return 0;
}
It appears that I had misunderstood exactly what was going on within javascript that was allowing this behavior to occur. After digging in deeper I see now that the only time variables are available within closures are when the variable definition is within the parent scope of the closure definition as such:
var funcB = function(funcA){
funcA();
};
(function(){
var firstVar = 1;
var secondVar = 2;
funcB(function(){
alert(firstVar + secondVar);
});
})();
This same behavior could be achieved using lambda capture (as suggested by user #Marek R in question comments) in C++ as follows:
void funcB(std::function<void()> funcA) {
funcA();
}
int main() {
int firstVar = 1;
int secondVar = 2;
funcB([&]() {
std::cout << firstVar + secondVar;
});
std::cin.get();
return 0;
}
Therefore my original question stemmed from not knowing what I didn't know. To achieve what I am actually after, I will have to pass parameters to my lambda or implement a different design pattern.
So I'm trying to write a recursive function that keeps track of how often it got called. Because of its recursive nature I won't be able to define an iterator inside of it (or maybe it's possible via a pointer?), since it would be redefined whenever the function gets called. So i figured I could use a param of the function itself:
int countRecursive(int cancelCondition, int counter = 0)
{
if(cancelCondition > 0)
{
return countRecursive(--cancelCondition, ++counter);
}
else
{
return counter;
}
}
Now the problem I'm facing is, that the counter would be writeable by the caller of the function, and I want to avoid that.
Then again, it wouldn't help to declare the counter as a const, right?
Is there a way to restrict the variable's manipulation to the function itself?
Or maybe my approach is deeply flawed in the first place?
The only way I can think of solving this, is to use a kind of "wrapper-function" that keeps track of how often the recursive function got called.
An example of what I want to avoid:
//inside main()
int foo {5};
int countToZero = countRecursive(foo, 10);
//countToZero would be 15 instead of 5
The user using my function should not be able to initially set the counter (in this case to 10).
You can take you function as is, and wrap it. One way I have in mind, which completely encapsulates the wrapping is by making your function a static member of a local class. To demonstrate:
int countRecursive(int cancelCondition)
{
struct hidden {
static int countRecursive(int cancelCondition, int counter = 0) {
if(cancelCondition > 0)
{
return countRecursive(--cancelCondition, ++counter);
}
else
{
return counter;
}
}
};
return hidden::countRecursive(cancelCondition);
}
Local classes are a nifty but rarely seen feature of C++. They possess some limitations, but fortunately can have static member functions. No code from outside can ever pass hidden::countRecursive an invalid counter. It's entirely under the control of the countRecursive.
If you can use something else than a free function, I would suggest to use some kind of functor to hold the count, but in case you cant, you may try to use something like this using friendship to do the trick:
#include <memory>
class Counter;
int countRecursive(int cancelCondition, std::unique_ptr<Counter> counter = nullptr);
class Counter {
int count = 0;
private:
friend int countRecursive(int, std::unique_ptr<Counter>);
Counter() = default; // the constructor can only be call within the function
// thus nobody can provide one
};
int countRecursive(int cancelCondition, std::unique_ptr<Counter> c)
{
if (c == nullptr)
c = std::unique_ptr<Counter>(new Counter());
if(cancelCondition > 0)
{
c->count++;
return countRecursive(--cancelCondition, std::move(c));
}
else
{
return c->count;
}
}
int main() {
return countRecursive(12);
}
You can encapsulate the counter:
struct counterRecParam {
counterRecParam(int c) : cancelCondition(c),counter(0) {}
private:
int cancelCondition;
int counter;
friend int countRecursive(counterRecParam);
};
Now the caller cannot modify the counter, and you only need to modify the function slightly:
int countRecursive(counterRecParam crp)
{
if(crp.cancelCondition > 0)
{
--crp.cancelCondition;
++crp.counter;
return countRecursive(crp);
}
else
{
return crp.counter;
}
}
And the implicit conversion lets you call it with an int
counterRecursive(5);
One way to do this is to use a functor. Here's a simple example:
#include <iostream>
class counter
{
public:
unsigned operator()(unsigned m, unsigned n)
{
// increment the count on every iteration
++count;
// rest of the function
if (m == 0)
{
return n + 1;
}
if (n == 0)
{
return operator()(m - 1, 1);
}
return operator()(m - 1, operator()(m, n - 1));
}
std::size_t get_count() const
{
return count;
}
private:
// call count
std::size_t count = 0;
};
int main()
{
auto f = counter();
auto res = f(4, 0);
std::cout << "Result: " << res << "\nNumber of calls: " << f.get_count() << std::endl;
return 0;
}
Output:
Result: 13
Number of calls: 107
Since the count is stored in the object itself, the user cannot overwrite it.
Have you tried using "static" counter variable. Static variables gets initialized just once, and are best candidates to be used as counter variables.
Is there any functional difference between the following 2 code snippets?
bool ColorClass::setTo(int inRed, int inGreen, int inBlue)
{
amountRed = inRed;
amountGreen = inGreen;
amountBlue = inBlue;
return clipColor(amountRed, amountGreen, amountBlue);
}
bool ColorClass::setTo(int inRed, int inGreen, int inBlue)
{
amountRed = inRed;
amountGreen = inGreen;
amountBlue = inBlue;
if (clipColor(amountRed, amountGreen, amountBlue))
{
return true;
}
else
{
return false;
}
}
The functions the above code calls are defined below:
bool ColorClass::clipColor(int &checkRed, int &checkGreen, int &checkBlue)
{
int numClips = 0; //numClips is used to counter number of clips made
checkColorBounds(checkRed, numClips);
checkColorBounds(checkGreen, numClips );
checkColorBounds(checkBlue, numClips);
return (numClips != 0);
}
void ColorClass::checkColorBounds(int &color, int &clipCounter)
{
if(color > MAXCOLOR)
{
color = MAXCOLOR;
clipCounter++;
}
else if (color < MINCOLOR)
{
color = MINCOLOR;
clipCounter ++;
}
}
I tested both and gone through both, and I can't seem to notice anything functionally different.
I like the first one better, because it is much more succint and more efficient (avoids the if-else)
There're no any functional differences at all. Then use the 1st one.
KISS
I am on visual c++ working on a console calculator, I am creating a way to let the user define a custom linear function. Here is where I am stumped: Once I get the users desired name of the function, the slope, and the y-intercept, I need to use that data to create a callable function that I can pass to muParser.
In muParser, you define custom functions like this:
double func(double x)
{
return 5*x + 7; // return m*x + b;
}
MyParser.DefineFun("f", func);
MyParser.SetExpr("f(9.5) - pi");
double dResult = MyParser.Eval();
How could I dynamically create a function like this based on the users input for the values 'm' and 'b' and pass that to the 'DefineFun()' method?
This is what I have so far:
void cb_SetFunc(void)
{
string FuncName, sM, sB;
double dM, dB;
bool GettingName = true;
bool GettingM = true;
bool GettingB = true;
regex NumPattern("[+-]?(?:0|[1-9]\\d*)(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?");
EchoLn(">>> First, enter the functions name. (Enter 'cancel' to abort)");
EchoLn(">>> Only letters, numbers, and underscores can be used.");
try
{
do // Get the function name
{
Echo(">>> Enter name: ");
FuncName = GetLn();
if (UserCanceled(FuncName)) return;
if (!ValidVarName(FuncName))
{
EchoLn(">>> Please only use letters, numbers, and underscores.");
continue;
}
GettingName = false;
} while (GettingName);
do // Get the function slope
{
Echo(">>> Enter slope (m): ");
sM = GetLn();
if (UserCanceled(sM)) return;
if (!regex_match(sM, NumPattern))
{
EchoLn(">>> Please enter any constant number.");
continue;
}
dM = atof(sM.c_str());
GettingM = false;
} while (GettingM);
do // Get the function y-intercept
{
Echo(">>> Enter y-intercept (b): ");
sB = GetLn();
if (UserCanceled(sB)) return;
if (!regex_match(sB, NumPattern))
{
EchoLn(">>> Please enter any constant number.");
continue;
}
dB = atof(sB.c_str());
GettingB = false;
} while (GettingB);
// ------------
// TODO: Create function from dM (slope) and
// dB (y-intercept) and pass to 'DefineFun()'
// ------------
}
catch (...)
{
ErrMsg("An unexpected error occured while trying to set the function.");
}
}
I was thinking that there isn't a way to define an individual method for each user-defined-function. Would I need to make a vector<pair<double, double>> FuncArgs; to keep track of the appropriate slopes and y-intercepts then call them dynamically from the function? How would I specify which pair to use when I pass it to DefineFun(FuncStrName, FuncMethod)?
What you need (in addition to a script language interpreter) is called a "trampoline". There is no standard solution to create those, in particular since it involves creating code at runtime.
Of course, if you accept a fixed number of trampolines, you can create them at compile time. And if they're all linear, this might be even easier:
const int N = 20; // Arbitrary
int m[N] = { 0 };
int b[N] = { 0 };
template<int I> double f(double x) { return m[I] * x + b; }
This defines a set of 20 functions f<0>...f<19> which use m[0]...m[19] respectively.
Edit:
// Helper class template to instantiate all trampoline functions.
double (*fptr_array[N])(double) = { 0 };
template<int I> struct init_fptr<int I> {
static const double (*fptr)(double) = fptr_array[I] = &f<I>;
typedef init_fptr<I-1> recurse;
};
template<> struct init_fptr<-1> { };
I would keep it simple:
#include <functional>
std::function<double(double)> f; // this is your dynamic function
int slope, yintercept; // populate from user input
f = [=](double x) -> double { return slope * x + yintercept; };
Now you can pass the object f to your parser, which can then call f(x) at its own leisure. The function object packages the captured values of slope and yintercept.
GiNaC is C++ lib which can parse and evaluate math expressions.
Generating a fixed array of functions bindable to boost function.
Someone else already said about a similar method, but since I'd taken the time to write the code, here it is anyway.
#include <boost/function.hpp>
enum {
MAX_FUNC_SLOTS = 255
};
struct FuncSlot
{
double (*f_)(double);
boost::function<double(double)> closure_;
};
FuncSlot s_func_slots_[MAX_FUNC_SLOTS];
template <int Slot>
struct FuncSlotFunc
{
static void init() {
FuncSlotFunc<Slot-1>::init();
s_func_slots_[Slot - 1].f_ = &FuncSlotFunc<Slot>::call;
}
static double call(double v) {
return s_func_slots_[Slot - 1].closure_(v);
}
};
template <> struct FuncSlotFunc<0> {
static void init() {}
};
struct LinearTransform
{
double m_;
double c_;
LinearTransform(double m, double c)
: m_(m)
, c_(c)
{}
double operator()(double v) const {
return (v * m_) + c_;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
FuncSlotFunc<MAX_FUNC_SLOTS>::init();
s_func_slots_[0].closure_ = LinearTransform(1, 0);
s_func_slots_[1].closure_ = LinearTransform(5, 1);
std::cout << s_func_slots_[0].f_(1.0) << std::endl; // should print 1
std::cout << s_func_slots_[1].f_(1.0) << std::endl; // should print 6
system("pause");
return 0;
}
So, you can get the function pointer with: s_func_slots_[xxx].f_
And set your action with s_func_slots_[xxx].closure_
Try to embed to your application some script language. Years ago I was using Tcl for similar purpose - but I do not know what is the current time best choice.
Either you can start from Tcl or search yourself for something better:
See: Adding Tcl/Tk to a C application