#include <iostream>
#include <functional>
using Callback = std::function<void(const int)>;
int main() {
Callback testCall = [](const int &num) {
std::cout << "callback: " << num << " - " << &num << std::endl;
};
int num = 42;
testCall(num);
std::cout << "main: " << num << " - " << &num << std::endl;
}
Possible output:
callback: 42 - 000000B19197F618
main: 42 - 000000B19197F694
As you can see, even if i assign a lambda function which takes the parameter by reference it still uses a copy.
Is that correct?
If yes, why does it still compile? Why is there at least not a warning about the discrepancy between the Callback declaration parameters and the assigned lambda. (const int &num vs const int num)
When not usingconst it does not compile.
PS. if you find a better title, feel free to edit.
This is because testCall is a functor object that catch its parameter by copy and then call the lambda on it.
Try:
Callback f = [](const int &num) {
std::cout << "callback: " << num << " - " << &num << std::endl;
};
int main() {
int num = 999;
std::cout << "callback: " << num << " - " << &num << std::endl;
f(num);
[](const int &num) {
std::cout << "callback: " << num << " - " << &num << std::endl;
}(num);
}
you will see something like:
callback: 999 - 0x7ffeed60a9bc
callback: 999 - 0x7ffeed60a994
callback: 999 - 0x7ffeed60a9bc
which means that callBack is not the function by itself but an indirection to the function. And there is no problem regarding types...
Answer to this may helps you to understand what happens under the hood: How std::function works
Related
I am trying to calculate the lpNorm of a vector with the Eigen library.
As it can be seen in the example below, with explicit values, such as v.lpNorm<1>(), it works. But it doesn't work inside the loop, with lpNorm<p>()
How can I fix this?
#include <iostream>
#include <Eigen/Dense>
using Eigen::VectorXd;
int main()
{
int sizev = 3;
int p;
Eigen::VectorXd v(sizev);
v(0) = 3.;
v(1) = 2.;
v(2) = 1.;
// test 1, passes
std::cout << "||v||_" << 1 << " = " << v.lpNorm<1>() << std::endl;
std::cout << "||v||_" << 2 << " = " << v.lpNorm<2>() << std::endl;
std::cout << "||v||_" << 3 << " = " << v.lpNorm<3>() << std::endl;
std::cout << "||v||_" << 4 << " = " << v.lpNorm<4>() << std::endl;
std::cout << "||v||_inf = " << v.lpNorm<Eigen::Infinity>() << std::endl;
// test 2, fails
for (int p=1; p<5; p++)
{
std::cout << "||v||_" << p << " = " << v.lpNorm<p>() << std::endl;
}
return 0;
}
On compilation, I am getting the error
error: no matching member function for call to 'lpNorm'
std::cout << "||v||_" << p << " = " << v.lpNorm<p>() << std::endl;
~~^~~~~~~~~
note: candidate template ignored: invalid explicitly-specified argument for template parameter 'p'
template<int p> EIGEN_DEVICE_FUNC RealScalar lpNorm() const;
^
1 error generated.
You cannot use variable integer as a template argument, it needs to be a compile time constant, such as
constexpr int p = 3;
v.lpNorm<p>();
However, you can still have a kind of compile-time loop using e.g. std::integer_sequence. I modified a bit the example from documentation to call a function:
template<typename T, T... ints>
void exec_constexpr_loop(std::integer_sequence<T, ints...> int_seq, Eigen::Ref<Eigen::VectorXd> v)
{
((v.lpNorm<ints>()), ...);
}
exec_constexpr_loop(std::integer_sequence<int, 1, 2, 3>{}, v);
Live demo with dummy function, works since C++17.
I am not sure how to explain this behaviour, displayed here with a minimal example.
Why isn't size correctly captured ?
#include <iostream>
#include <vector>
using namespace std;
auto&& matcher1KO = [] (vector<int> &v){
int size = v.size();
cout << "size outside : " << size << "\n"; // print 1
return [&] (bool b) {
cout << "v.size() : " << v.size() << "\n"; // print 1
cout << "size inside : " << size << "\n"; // print 0
};
};
auto&& matcher2OK = [] (vector<int> &v){
int size = v.size();
cout << "size outside : " << size << "\n"; // print 1
return [&] () {
cout << "v.size() : " << v.size() << "\n"; // print 1
cout << "size inside : " << size << "\n"; // print 1
};
};
int main() {
vector<int> v {+1};
auto matcherf1 = matcher1KO(v); //
matcherf1(true);
auto matcherf2 = matcher2OK(v);
matcherf2();
}
Both the code have undefined behavior, anything is possible.
The reason is the same for the two cases: the variable size is a local object inside the operator() of the lambda, it will be destroyed when the invocation ends. You're capturing size by-reference and the reference is dangled.
Changing it to capture-by-value would be fine. e.g.
return [=] (bool b) {
cout << "v.size() : " << v.size() << "\n"; // print 1
cout << "size inside : " << size << "\n"; // print 1
};
you know that the compiler transforms a lambda expression into some kind of functor:
the captured variables become data members of this functor. Variables captured by value are copied into data members of the functor. These data members have the same constness as the captured variables et cetera...
Now I wonder if it's possible to catch the address of this hidden object generated from the compiler behind the scenes
I give you a simple snippet of (WRONG) code just to show my intentions:
#include <iostream>
using namespace std;
class MetaData
{
public:
void printAddress()
{
cout << "\n printAddress:Instance of MetaData at &" << this;
}
};
int main()
{
MetaData md1;
cout << "\n &md1 = " << &md1 << "\n";
md1.printAddress();
cout << "\n\n--------------------\n\n";
int i = 5;
auto x = [i]() mutable {
//cout << "\n The address of the functor is &" << this; // ERROR ! ! !
cout << "\n Hello from Lambda ";
cout << "\n &i = " << &i << " ++i ==> " << ++i << endl; };
x(); // executing lambda
auto y = x; // y is constructed with copy ctor
y();
}
Link to Coliru
I'd like hidden functor to behave like MetaDatas.
Can someone clear my mind?
Thanks for your time.
Syntax would be:
auto x = [&](){ std::cout << &x; }; // but it is illegal too:
// variable 'x' declared with deduced type 'auto' cannot appear in its own initializer
Possible work-around is usage of Y-combinator, something like:
auto x = [i](auto& self) mutable {
cout << "\n The address of the functor is &" << &self;
cout << "\n Hello from Lambda ";
cout << "\n &i = " << &i << " ++i ==> " << ++i << endl; };
x(x); // executing lambda
Demo
So my question is pretty simple, tho I haven't been able to find an answer already so I'm asking here.
I curious to know whether I can return an std:: pair reference from a function, and have the calling function modify its values. Here's an example of what I mean:
struct PairStruct {
using PairType = std::pair<size_t, size_t>;
PairStruct() : m_pair(std::make_pair(0, 0)) {}
void modifyRefInternal() {
auto pair = getPairRef();
std::cout << "start - first: " << pair.first << ", second: " << pair.second << "\n";
pair.first++;
pair.second++;
std::cout << "end - first: " << pair.first << ", second: " << pair.second << "\n";
}
void modifyPtrInternal() {
auto pair = getPairPtr();
std::cout << "start - first: " << pair->first << ", second: " << pair->second << "\n";
pair->first++;
pair->second++;
std::cout << "end - first: " << pair->first << ", second: " << pair->second << "\n";
}
PairType &getPairRef() {
return m_pair;
}
PairType *getPairPtr() {
return &m_pair;
}
PairType m_pair;
};
int main(int argc, char ** args)
{
PairStruct *pairInst = new PairStruct;
// Test with reference
std::cout << "Reference test.\n";
pairInst->modifyRefInternal();
std::cout << "\n";
pairInst->modifyRefInternal();
std::cout << "\n";
// Test with ptr
std::cout << "Ptr test.\n";
pairInst->modifyPtrInternal();
std::cout << "\n";
pairInst->modifyPtrInternal();
delete pairInst;
return 0;
}
As expected when I use a pointer it correctly modyfies the values, this is not the case when returning a reference. Here's the output of this program:
Reference test.
start - first: 0, second: 0
end - first: 1, second: 1
start - first: 0, second: 0
end - first: 1, second: 1
Ptr test.
start - first: 0, second: 0
end - first: 1, second: 1
start - first: 1, second: 1
end - first: 2, second: 2
This is going to seem very trivial, however, I'd like to know why I can't use the referenced pair in this case. Thanks!
With
auto pair = getPairRef();
the variable pair is deduced as a value, not a reference.
You need to explicitly make it a reference:
auto& pair = getPairRef();
Just write in the member function modifyRefInternal
decltype(auto) pair = getPairRef();
^^^^^^^^^
I have been searching on Google an in this forum for a while, but I could not find any answer or tip for my problem. Tutorials couldn't help me either...
I want to redistribute some points, stored in a vector p_org. (x-value is stored as double).
Therefore I have the function distribute, which is defined in maths.h
distribute_tanh(&p_org_temp,&p_new_temp,iz,spacing[0],spacing[1],l_rot[(kk+1)*iz-2],status);
The function distribute_tanh does look like this:
inline void distribute_tanh (std::vector<double> *p_org, std::vector<double> *p_new, const int n_points, double spacing_begin, double spacing_end, const double total_length, double status){
//if status == 0: FLAP, if status == 1: SLAT
std::cout << "spacing_begin: " << spacing_begin << " spacing_end: " << spacing_end << std::endl;
double s_begin = spacing_begin / total_length;
double s_end = spacing_end / total_length;
double A = sqrt(s_end/s_begin);
double B = 1 / (sqrt(s_end*s_begin)*n_points);
std::cout << "A: " << A << " B: " << B << std::endl;
std::vector<double> u (n_points);
std::vector<double> sn (n_points);
double dx;
double dy;
std::cout << "Control at the beginning: p_org: " << (p_org) << " p_new: " << (p_new) << " n_points: " << n_points << " s_begin: " << s_begin << " s_end: " << s_end << " total_length: " << total_length << std::endl;
//problem no. 1
for (int i=0;i<n_points;i++){
if (B > 1.001) {
if (B < 2.7829681) {
double Bq=B-1;
dy=sqrt(6*Bq)*(1-0.15*Bq+0.057321429*pow(Bq,2)-0.024907295*pow(Bq,3)+0.0077424461*pow(Bq,4)-0.0010794123*pow(Bq,5));
} else if (B > 2.7829681) {
double Bv=log(B);
double Bw=1/B-0.028527431;
dy=Bv+(1+1/Bv)*log(2*Bv)-0.02041793+0.24902722*Bw+1.9496443*pow(Bw,2)-2.6294547*pow(Bw,3)+8.56795911*pow(Bw,4);
}
u[i]=0.5+(tanh(dy*(i*(1.0/n_points)-0.5))/(2*tanh(dy/2)));
}
else if (B < 0.999) {
if (B < 0.26938972) {
dx=M_PI*(1-B+pow(B,2)-(1+(pow(M_PI,2))/6)*pow(B,3)+6.794732*pow(B,4)-13.205501*pow(B,5)+11.726095*pow(B,6));
} else if (B > 0.26938972) {
double Bq=1-B;
dx=sqrt(6*Bq)*(1+0.15*Bq+0.057321429*pow(Bq,2)+0.048774238*pow(Bq,3)-0.053337753*pow(Bq,4)+0.075845134*pow(Bq,5));
}
u[i]=0.5+(tan(dx*(i*(1.0/n_points)-0.5))/(2*tan(dx/2)));
}
else {
u[i]=i*(1.0/n_points)*(1+2*(B-1)*(i*(1.0/n_points)-0.5)*(1-i*(1.0/n_points)));
}
sn[i]=u[i]/(A+(1.0-A)*u[i]);
std::cout << "sn(i): " << sn[i] << std::endl;
std::cout << "p_org[n_points]: " << &p_org[n_points-1] << std::endl;
if(status==0){
//p_new[i]=p_org[0]+(total_length*sn[i]);
std::cout << "FLAP maths.h" << std::endl;
}
//Here is the problem no. 2
else if(status==1){
//p_new[i]=p_org[0]-(total_length*sn[i]);
std::cout << "SLAT maths.h" << std::endl;
}
//std::cout << "p_new in math: " << p_new << std::endl;
}
}
My problem is, that I am unable to access the value of p_org or p_new. At the beginning I would like to give out the value of p_org and p_new. If I try it with a *, the compiler is complaining: error: no operator "<<" matches these operands
operand types are: std::basic_ostream> << std::vector>
std::cout << "Control at the beginning: p_org: " << (*p_org) << " p_new: " << (*p_new) << " n_points: " << n_points << " s_begin: " << s_begin << " s_end: " << s_end << " total_length: " << total_length << std::endl;
If I leave the * off, I get the addresses of p_org and p_new.
At the end of the code I would like to write the new value to p_new. If I use * to access the value, the compiler is complaining, if I leave it off, its complaining too with the following message:
error: no operator "-" matches these operands
operand types are: std::vector<double, std::allocator<double>> - double
p_new[i]=p_org[0]-(total_length*sn[i]);
^
I tried to understand both problems, but until now I had no success.
Thanks for your advice.
Your issue with the compiler error can be cut down to a very simple program.
#include <vector>
void foo(std::vector<int>* pV)
{
pV[0] = 10; // error.
}
int main()
{
std::vector<int> v(10);
foo(&v);
}
The issue is that operator[] as done above works for objects and references, not pointers. Since pv is a pointer, you must dereference it first to obtain the object, and then apply [] to the dereferenced pointer.
void foo(std::vector<int>* pV)
{
(*pV)[0] = 10; // No error
}
The other form of calling operator[] can be also used, but is a bit more verbose:
void foo(std::vector<int>* pV)
{
pv->operator[](0) = 10; // No error
}
However, to alleviate having to do this, pass the vector by reference. Then the "normal" way of using operator[] can be used.
#include <vector>
void foo(std::vector<int>& pV)
{
pV[0] = 10; // No error.
}
int main()
{
std::vector<int> v(10);
foo(v);
}