I recently stumbled upon this example code and I was confused:
auto named_funct(const MyClass& some_class)
{
return [some_class](const MyClass2& some_other_class)
{
return some_class <= some_other_class; // some expression between capture and input parameter to the Lambda
};
}
Is there any reason at all to wrap an anonymous function in a named function? It seems like an extra function call stack is being created for no reason.
named_funct doesn't execute the lambda, it returns it. You could use it like this:
auto it = std::find_if(std::begin(some_vector), std::end(some_vector),
named_funct(some_instance));
The odd thing is that named_funct takes a parameter that it doesn't do anything with, unless you have a copy/paste error (another instance is passed to the actual lambda). This example is also so trivial I don't see the benefit of a lambda, but if named_funct's argument was captured and used somehow, this is a useful pattern.
There can be a reason (if, for example, you want partial functions (the ability to do f(x)(y) rather than f(x, y))), but there isn't here. The outer input argument is shadowed by the argument of the anonymous function.
To add another possible (slightly modified) use case for this pattern:
you could return different implementations of the lambda even with different return types based on templated traits like in following example
#include <iostream>
#include <string>
enum class MyTrait
{
Default,
Other
};
struct Foo
{
std::string Baz() const { return "bar"; };
int Bazz() const { return 42; };
};
template <MyTrait>
struct LambdaGenerator;
template <>
struct LambdaGenerator<MyTrait::Default>
{
auto operator()(const Foo& foo) const { return [&]{ return foo.Baz(); }; }
};
template <>
struct LambdaGenerator<MyTrait::Other>
{
auto operator()(const Foo& foo) const { return [&]{ return foo.Bazz(); }; }
};
int main()
{
std::cout << LambdaGenerator<MyTrait::Default>()(Foo())() << std::endl;
std::cout << LambdaGenerator<MyTrait::Other>()(Foo())() << std::endl;
// prints
// bar
// 42
}
I quite often used this when working with C++ AMP to implement different variants of GPU targeted algorithms (which in AMP are lambda objects).
Related
It seems you can return an unnamed struct this way:
auto foo() {
struct {
int bar;
int square() {
return bar * bar;
}
} a { 7 };
return a;
}
Is there anyway to do this without the redundant variable name a, thus anonymously?
For starters C++ does not define anonymous structures. I think you mean an unnamed structure.
According ro the C++ Standard the return statement is defined like (8.6 Jump statements)
return expr-or-braced-init-listopt ;
So you may not use a declaration in the return statement. If so then you need prelimary to declare an object of the structure type that will be returned.
I have no idea what the point of this exercise is, so here is an answer that technically does what you ask for:
auto helper()
{
struct {
int x;
} a {0};
return a;
}
decltype(helper()) foo()
{
return {8};
}
https://godbolt.org/z/zA8C1V
The struct is unnamed.
foo does not return a named variable.
Of course this is straight up ridiculous - one would just name the struct instead of this decltype tomfoolery.
No, this is not possible.
The closest you can get is to use a functional-style cast to create a temporary, and use a C99-style scoped-initialiser; GCC allows this in C++ mode, as an extension:
#include <iostream>
#include <string>
auto foo() {
return (struct {
int bar;
int square() {
return bar * bar;
}
}) { 7 };
}
… but this is not portable (and will warn).
Without the braces around 7 the extension is not triggered, and you're back to standard code, in which it is illegal to define a type in a cast.
Instead of writing obtuse code, give your type a name and give your object a name. Your readers will thank you.
None of
struct {/*...*/} foo() { // Illegal
return {/*...*/};
}
auto foo() {
return struct { /*...*/ } { /*...*/ }; // Illegal
}
template <typename T = struct { /*...*/ }> // Illegal
T foo() {
return { /*...*/ };
}
are legal.
You have to, at least, have a named type, or a named instance.
Lambda allows to have neither, but you can only capture and define its operator():
auto foo() {
return [/*...*/](/*...*/) { /*...*/ }; // Legal
}
Returning anonymous struct
There is no such thing as anonymous struct in C++. That's enough to make it impossible.
There is a - limited - way of returning an object of anonymous type from a function: Returning a lambda.
auto make_square_function() {
return [bar = 7]() {
return bar * bar;
};
}
Lambdas are much more limited than general classes though. The members (captures) are encapsulated and cannot be named from the outside of the lambda and there are no member functions other than the function call overload.
Is there anyway to do this without the redundant variable name a
Only if you give the class a name:
struct Squarer {
int bar;
int square() {
return bar * bar;
}
};
auto foo() {
return Squarer{7};
}
Returning an instance of unnamed class is only possible by defining a variable.
Just for fun, another define-the-variable-in-another-function solution (taking inspiration from Max Langhof's answer)
auto foo ()
{
return []{ struct{int bar;} a {7}; return a; }();
}
No, because you need to return an instance of an object, in this case a.
The returned object has to exist somewhere in memory, you can't just return a class definition.
In your example, you don't return an anonymous struct, but you return an instance of that struct.
I was trying to play around with std::function and std::bind and I stepped in a problem. I would like to build a general structure that allows me to bind a std::function to a member function without knowing a priori the arguments of the member function. I wrote this thing
template<typename Class, typename Return, typename ...Args>
struct Caller
{
private:
std::function<Return(Args ...)> callerFunction;
Caller(const Caller&) = delete;
Caller(Caller&&) = delete;
Caller& operator=(const Caller&) = delete;
public:
~Caller() = default;
Caller() = default;
Caller(Class& instance, Return(Class::*function)(Args...))
{
callerFunction = [&](Args... args) { return (instance.*function)(args...); };
}
Return operator() (Args ... args)
{
return callerFunction(args...);
}
};
FYI I know that the arguments to the function are passed by value (I encountered some problem using universal references with variadic template, I will work on that later).
The problem here is that when I fire the function with operator() I get an Access Violation Error. I tried to narrow down the problem and created a structure without the variadic arguments (allowing the member function to have just an int as argument) and I saw that assigning the lambda to the std::function was given me the same error, but if I used std::bind with a placeholder everything was just fine.
The test ground is this
class A
{
public:
bool foo(int a)
{
std::cout << a << std::endl;
return true;
}
};
int main()
{
A a;
a.foo(9);
Caller<A, bool, int> caller(a, &A::foo);
caller(10);
std::cin.ignore();
}
Using the lambda, do I need to save the instance of the class in order to call properly the member function?
As state in comment, you have dangling pointer of function, you could use instead:
Caller(Class& instance, Return(Class::*function)(Args...))
{
callerFunction = [&instance, function](Args... args) {
return (instance.*function)(std::forward<Args>(args)...);
};
}
Note: instance should also outlives Caller.
Don't use [&] when the object or copies of it outlives the current scope.
You are capturing references to local variables and storing them beyond the current scope.
I am trying to write a general integral function and I would like to implement it in such a way so that it can accept any mathematical function. That is, I would like to pass the math function as an input parameter. In pseudo-code: simpson_int(x*x). I've heard of the function template in <functional> but I don't really have experience with templates in C++.
There are some solutions that comes in my mind (and this is my approach at the problem, for sure there are more solution, and maybe what I'm pointing out is not the best), that consider the fact that you need to call the argument function more than once in the Simpson implementation (thus you need a "callable" argument):
Function pointer
Function pointers (more C than C++), where you declare with two arguments: the first one will be the pointer to a function with the specified types, while the second is the argument for your function. Lets
make an example:
#include <iostream>
double power2(double x) {
return x * x;
}
double simspon(double (*f)(double), double x) {
return f(x);
}
int main() {
std::cout << simspon(power2, 2);
return 0;
}
In this case I have used no templates for reaching the result. But this will not take any function as first argument, but only a function that has as argument a double and returns a double.
I think that most of c++ programmer will suggest you to avoid this method.
Function pointer and templates
So you maybe want to expand the previous example using templates and making it more general. It is quite simple to redefine the function
to accept a template (an abstract type) that you actually specify only when you use it in your code:
#include <iostream>
double power2(double x) {
return x * x;
}
int power2int(int x) {
return x * x;
}
template <class T, class P>
P simspon(T (*f)(P), P x) {
return f(x);
}
int main() {
std::cout << simspon<double, double>(power2, 2.0);
std::cout << simspon<int, int>(power2int, 2);
return 0;
}
T and P are two templates: the first one is used for describing the returned value of the function pointer, while the second specify the argument of the function pointer, and the returned value of simpson.So when you are writing template <class T, classP> you are actually informing the compiler that that you are using T and P as placeholder for different type. You will actually declare the type that you want later on, when you will call the function in the main. This is not good code but I'm building the path to understand templates. Also, you specify the type of your argument function when you actually call simpson, with the < >.
(Disclaimer: you should consider to use template <typename T ...> instead of class. But I'm used with the old class and there are situation in which typename cannot be used, there are a lot of questions on SO that dive into this.)
Using std::function
Instead of using a function pointer as argument you may want to create a variable that stores your function to be passed as argument of simpson. This bring several advantages, because they are actually an object inside your code that have some predictable behavior in some unwanted circumstances (for example, in case of a null function pointer you have to check the pointer itself and handle it, in case of std::function if there is no callable pointer it throws std::bad_function_call error)
Here an example, and it uses again templates, as before:
#include <iostream>
#include <functional>
double power2(double x) {
return x * x;
}
int power2int(int x) {
return x * x;
}
template <class T, class P>
P simspon(std::function<T(P)> f, P x) {
return f(x);
}
int main() {
std::function<double(double)> p_power2 = power2;
std::cout << simspon<double, double>(p_power2, 2.0);
std::function<double(double)> p_power2int = power2int;
std::cout << simspon<int, int>(power2int, 2);
return 0;
}
Using lambdas
lambdas are closure and in your case (if you can use the standard C++14) can be used alongside the auto keyword to achieve quite a general behavior, without the explicit use of templates. The closure are also able to capture part/the whole context, check the reference for this.
Let's see an example, in which I create two lambdas that receive different arguments and a simpson function that is quite general (actually it is not, is the compiler that defines different functions with respect to the call that you do).
#include <iostream>
auto lambda = [](auto x) { return x * x ; };
auto lambda_2 = [] (int x) { return x + 10; };
auto simpson(auto f, auto x) {
return f(x);
}
int main() {
std::cout << simpson(lambda, 2.0);
std::cout << simpson(lambda_2, 1);
return 0;
}
You need to compile it with the -std=c++14 flag. There are tons of advise that comes in my mind to suggest you to avoid to implement your code in this way, remember that it has only some illustrative purposes (I've more than exaggerated with the auto keyword).
Function objects (the Problem class)
Maybe an improvement for your case is to write a general class for the mathematical functions to integrate and pass the object to your function. This bring several advantages: you may want to save some of the integrative result inside your function or even write the stream operator to pretty print your problem. This is the solution employed typically by mathematical libraries.
In this extremely simple case, we have a class that is a problem. When you create a new instance for this class, a std::function is passed to the constructor and stored inside the class. The instance of the class is the argument for your simpson:
#include <iostream>
#include <functional>
template <class T, class P>
class Problem {
public:
// Attributes
std::function<T(P)> _f;
// Constructor
Problem(std::function<T(P)> f) : _f(f) {};
// Making the object callable
P operator()(P x) { return _f(x); }
};
template <class T, class P>
P simspon(Problem<T, P> p, P x) {
return p(x);
}
int main() {
Problem<double, double> prb([](double x) { return x * x; });
std::cout << simspon<double, double>(prb, 2);
return 0;
}
Use std::function, like this for example:
#include <iostream> // std::cout
#include <functional> // std::function
int main()
{
std::function<double(double)> simpson_int =([](double x) { return x * x; };
std::cout << "simpson_int(4): " << simpson_int(4) << '\n';
return 0;
}
which outputs:
simpson_int(4): 16
I have to store arguments (parameter pack), and pass the arguments to another function.
As a result, I cannot use lambda. And a good choice is std::bind.
But for this code
struct A{};
void test(A &&){}
int main()
{
A a;
test(move(a)); //work
bind(test,a)(); //compile fail; copy a to std::bind, pass a to test
}
According to standard, all variables stored in std::bind will be pass as lvalue to function. (The C++ standard doesn't say that, by I think that is what it means.)
And that means I cannot use a function (has rvalue reference in parameter) with std::bind.
One solution is to change test(A &&) to test(A &), but this only works for your project (and make it strange while you not only need to call test by std::thread but also need to call test by plain sequential call).
So, is there any ways to solve this problem?
You can create wrapper which will be convertible to the rvalue reference (like reference_wrapper/l-value references) and use it with bind:
It cal look like that:
#include <iostream>
#include <functional>
struct A{};
void test(A &&){ std::cout << "Works!\n"; }
template <typename T>
struct rvalue_holder
{
T value;
explicit rvalue_holder(T&& arg): value(arg) {}
operator T&&()
{
return std::move(value);
}
};
template <typename T>
rvalue_holder<T> rval(T && val)
{
return rvalue_holder<T>(std::move(val));
}
int main()
{
A a;
test(std::move(a)); //work
auto foo = std::bind(test, rval(std::move(a))); //works
foo();
}
http://coliru.stacked-crooked.com/a/56220bc89a32c860
Note: both rvalue_holder and especially rval need further work to ensure efficiency, robustness and desired behavior in all cases.
I'm new to C++11 thread , when reading a tutorial , I see a piece of code like this.
#include <thread>
#include <iostream>
using namespace std;
class background_task
{
public:
void operator()() const
{
cout<<"This is a new thread";
}
};
int main()
{
background_task f;
std::thread my_thread(f);
my_thread.join();
}
The output will be "This is new thread", but i don' really understand what does the function "operator()() const" mean?. In this case, it acts really the same with the constructor, is it right?.
And how can C++ have a syntax like that? I have search about related topic by using the search engine but no found no result.
Thanks in advanced.
void operator()() means an instance of the class with that operator can be called with function call syntax, with no return value, and without any parameters. For example:
background_task b;
b(); // prints "This is a new thread"
The operator() part indicates it is a call operator, the second set of empty parentheses () indicate the operator has no parameters. Here is an example with two parameters and a return value:
struct add
{
int operator()(int a, int b) const { return a + b; }
};
add a;
int c = a(1, 2); // c initialized to 1+2
Note that this syntax pre-dates C++11. You can create callable types (also referred to as functors) in C++03. The connection with C++11 is that the std::thread constructor expects something that can be called without arguments . This could be a plain function
void foo() {}
a static member function
struct foo {
static void bar() {}
};
an instance of a type such as background_task, a suitable lambda expression, a suitable invocation of std::bind, in short, anything that can be called without arguments.
It's just operator overloading and has nothing to do with C++11 or multi-threading. An overloaded operator is just a normal function with a funny name (this may be a bit oversimplified, but it's a good rule of thumb for beginners).
Your class has a function named (). That's all. Technically, you could as well have named the function foo or f or TwoParentheses.
Consider a simpler example:
#include <iostream>
class Example
{
public:
void operator()() { std::cout << "()"; }
void foo() { std::cout << "foo"; }
void TwoParentheses() { std::cout << "TwoParentheses"; }
};
int main()
{
Example e;
e.operator()();
e.foo();
e.TwoParentheses();
}
Now calling an overloaded operator like in this example in main, spelling out the entire .operator() part, is pretty pointless, because an overloaded operator's purpose is to make the calling code simpler. You would instead invoke your function like this:
int main()
{
Example e;
e();
}
As you can see, e(); now looks exactly as if you called a function.
This is why operator() is a special name, after all. In a template, you can handle objects with operator() and function pointers with the same syntax.
Consider this:
#include <iostream>
class Example
{
public:
void operator()() { std::cout << "Example.operator()\n"; }
};
void function() { std::cout << "Function\n"; }
template <class Operation>
void t(Operation o)
{
o(); // operator() or "real" function
}
int main()
{
Example object;
t(object);
t(function);
}
This is the reason why operator() is an important function in C++ generic programming, and is often required.
It has nothing to do with C++11, it's the function call overload operator. That means if you have a class like yours, you can create an instance of it and use as a function:
int main()
{
background_task bt;
bt();
}
The above main function should give the same result as your simple thread example.
it is operator over loading. the user provide an additional use to () operator. Example for static polymorphism. it is fearture of Object orieted program