Can't construct std::function with brace initialization [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 months ago.
Improve this question
EDIT: I was being dumb. The functionMaker call is shockingly a function not a constructor, so the braces obviously don't work.
So I have what is basically a factory function for producing a std::function from int to int, a quick minimal example is
std::function<int(int)> functionMaker(int x) {
return [x](int foo){return foo*x;};
}
Basically, I want to bind some values into the function (kind of like currying), and then call it later.
I want to use it through something like
functionMaker{2}(10)
But it errors me.
I verified that
functionMaker(2)(10)
works
And I explored what happens if I stored the function and then called it.
auto fct = functionMaker{2};
std::cout << fct(10) << std::endl;
fails, but
auto fct = functionMaker(2);
std::cout << fct(10) << std::endl;
works.
So it seems like braces just don't work here. What's going on? To reiterate, I would like to call it with something like functionMaker{2}(10). This way it's a bit easier for me to read which part is the construction and which part is the calling. What am I missing here?

If you'd like functionMaker{} to work, then functionMaker needs to be a class/struct. Functions can only take arguments via (). However, it's relatively easy to make it a class:
struct functionMaker
{
functionMaker(int x)
: f([x](int foo){return foo*x; }) {}
int operator()(int foo) { return f(foo); }
std::function<int(int)> f;
};
It's a bit more clumsy, but you only need to write it once; you can even generalize it to be like, make_functionMaker(f, ...).
Note that you can save std::function's overhead by simply implementing the function in operator().

Related

can't return a vector of objects in a fuction due to destructors [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm having some issue with returning vectors of objects of a class in functions because everytime my destructor erases the data twice and all the code just dies when the functions ends
here a simple code I wrote just to show my problem:
#include <iostream>
#include <vector>
using namespace std;
class identity{
public:
string name;
identity(string Name);
~identity();
};
vector<identity> function();
int main(){
function();
cout << "Hello world!";
}
identity::identity(string Name)
: name{Name}{
cout << "Object created!" << endl;
}
identity::~identity(){
cout << "Object " << name << " destroyed!" << endl;
}
vector<identity> function(){
identity me("Isaias");
}
in this case the cout "Hello world" doesn't work and the program always ends with "Object" without displaying the name like this:
Object created!
Object Isaias destroyed!
Object
and then the program just stops. I kind of fixed the problem by seting the type of the function to "void" or anything else instead of "vector" but I'd like to know why this problem occurs. Also I'm new to programming in general and in this community so I'm sorry if I'm not doing this in the right way.
I'd like to thank you all for your attention before anything and sorry again if i am messing everything up here.
vector<identity> function(){
identity me("Isaias");
}
The behaviour of the program is undefined because you don't return anything from the function even though you've declared that the function returns a vector<identity>.
To fix the bug, return a value. Example:
using namespace std::string_literals;
return {"Isaias"s};
Another bug is that you've chosen to use using namespace std, but you've declared identity which is an identifier that is already in the std namespace. This makes the program ambiguous and ill-formed.
To fix this, choose another name for the class, such that the name doesn't conflict with any of the current or future names in the std namespace. This is very difficult because there are many names in std and you cannot predict the future. There is a simpler solution though! Simply don't use using namespace std.
Third bug is that you've used std::string without including the header that defines it. The consequence is that the program may not necessarily compile in any current or future language implementation.
Solution: Include the header <string>.

Inside method but loop still getting expected unqualified-id error C++ [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I have a quick question. I have read about "expected unqualified-id" errors and how they occur when a loop is outside of a method. The issue I am having is that the loop is inside a method and I am still getting this? Any assistance would be greatly appreciated.
The error in compiler:
expected unqualified-id
for(auto template : filtered) {
^
The code:
py::str process(string text){
//some code...
for(auto template : filtered) {
//some more....
}
//a return
}
template is a reserved keyword. It's one of the few names you are not allowed to use. Change the name of your template variable to any legal identifier to fix your problem. For example, try :
py::str process(string text){
//some code...
for(auto my_template : filtered) {
//some more....
}
//a return
}

How to return error code from the main function in C++? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am working on an object-oriented C++ coursework where I need to return error codes from the main function. How would one do this properly?
Unfortunately this is an assessed coursework so I cannot post my code here. But let's say the case is as follows:
I'm building an enigma machine with classes Plugboard, Reflector, and Rotor. I pass each of the configuration files as arguments in the command line. In this task, I'm provided with a file errors.h containing the following:
#define INSUFFICIENT_NUMBER_OF_PARAMETERS 1
#define INVALID_INPUT_CHARACTER 2
#define INVALID_INDEX 3
// and so on...
So I have in my program several functions to check the errors, for example a function to check whether the configuration file contains an invalid character (it has to be 0 to 25). I was thinking of setting this as a boolean function and then in my main function have the following:
if (!plugboard.check_invalid_character(/*some arguments*/)) {
cerr << "Invalid character!" << endl;
return 2;
}
But I'm not completely sure this is the right way to do it? Is it too superficial? Is there a more elegant way of returning error?
I hope my question is a little clearer this time. Thanks before.
You just need to return the value 4 in your main method like this:
int main() {
return 4;
}
Please note that your main function could also have the arguments vector and the argument count so there could be more in the brackets.
If KLibby is right and you use a method with returns the value you need to use something like that:
int doSomething() {
return 4;
}
int main() {
return doSomething();
}

Is there a coding style that explicitly mentions parameter names in calls? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
When I pass some flags to a function, only their values are visible in the function call. The programmer has to look up what the values are corresponding to in the function definition. That often means to look at a different location or start typing the function call again for the IDE hints to show up.
// function definition in header file
void foo(bool output = false, bool formatted = false, bool debug = false);
// function call, it is not intuitive what the values mean
foo(true, false, true);
Is there a coding technique to approach this problem? For example, this pseudo code would be more intuitive, but that obviously isn't valid C++.
// function call with explicit mention of flags that should be true
foo(output, debug);
I know that there are many options for explicitly mentioning the options, often with an overhead of needed computation or syntax, like using a std::unordered_map of options. The syntax overhead becomes less with C++11 initializer lists. However, I would like to stick to a common practice if that exists.
In C++11, you could use scoped enumerations:
foo(output::yes, formatted::no, debug::yes);
(If you're stuck in the past, you can do something similar, but less elegant, with regular enumerations).
There's also the old-school method of combining single-bit flag values:
enum {
output = 1 << 0,
formatted = 1 << 1,
debug = 1 << 2
};
foo(output | debug);
The way I prefer is simply not to overload on bools in the user interface:
foo( /* non-bool parms ... */);
foo_formatted( /* non-bool parms ... */);
foo_debug( /* non-bool parms ... */);
with perhaps a hidden implementation with overloading as in OP's question.
You could use Named Parameter Idiom.
struct call_foo {
call_foo& formatted() { formatted_ = true; }
call_foo& debug() { debug_ = true; }
call_foo& output() { output_ = true; }
~call_foo() { foo(output_, formatted_, debug_); }
private:
bool formatted_ = false;
bool debug_ = false;
bool output = false;
};
Usage:
call_foo().debug().formatted();
You can extend it so that methods of call_foo take parameters, too.
I have seen three different ways to handle such situations in differnet coding styles:
Add comments explaining the semantics:
foo(true /* with output */, false /* not formatted */, debug /* debug on* /);
Use a macro which always expands to true and which takes an argument giving the semantics, e.g.
#define K(Name) true
foo(K(Output), !K(Formatted), K(Debug));
Use enums (this requires changing the signature of the function):
enum OutputMode { WithOutput, WithoutOutput };
enum FormattingMode { WithFormatting, WithoutFormatting };
enum DebugMode { WithDebug, WithoutDebug };
foo(WithOutput, WithoutFormatting, WithDebug);
If I have to use interfaces like foo, I usually end up with the first version. When designing APIs, I try to avoid having functions taking more than one bool - and if I do want it, I like the third version because it's type safe.

Under what circumstances is it feasible to use exception handling? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I have seen many exception handling mechanisms where they simply weren't necessary. A lot of the times the problem could have been solved in a much cleaner way using simple if statements.
For example, things like:
Invalid input
Division by zero
Wrong type
Container range check
Null pointer
Uninitialized data
... and so on.
Could someone provide an example where it would be a better approach to handle exceptions?
Exceptions become more important as your program size grows.
With a simple application return codes are probably fine. But when an error condition needs to bubble up a couple levels of the stack before being handled, it starts to make sense to use exceptions instead of passing error codes from every function.
Also, when a method already returns a value, it may not be practical or possible to return an error code from the function as well.
Sometimes using exception is cleaner. In function foo thanks to exception throwing in check function you can avoid checking what check returns what makes this function simpler:
#include<iostream>
using namespace std;
class A{
public:
int a_foo(int index){return _tab[index];}
private:
static int _tab[3];
};
int A::_tab[3]={1,2,3};
void check(int index)
{
if (index < 0 || index > 2)
throw string("invalid index");
}
void foo(A a, int index){
check(index);
cout << a.a_foo(index) << endl;
}
int main()
{
try
{
A a;
foo(a,4);
}
catch(string ex)
{
cerr << ex <<'\n';
}
}
I would use it when the consequence of some unexpected 'event' is inability for application to continue running. When it happens and you catch it, report it nicely and close the application (or whatever you think you should do in that case).