Pass by references? - c++

In the code below, I do not understand the difference between the two versions. In both cases, I make a passage by reference, it seems to me (I think).
Moreover, I do not understand why version 2 works, because for what I understand for the moment, the sign & allows me to give the address of a variable, so when I put function_name(int &yourInt) I technically ask the user to enter the address of an int? So I should call it like function_name(&myInt)? But here we call the function like function_name(myInt) instead.
Version 1 :
int value(int tab[], int *valeur)
{
for (int i = 0; i < 5; i++)
{
*valeur += tab[i];
}
return *valeur;
}
int main()
{
int test = 0;
int tab[10] = { 1,2,3,4,5};
std::cout << value(tab, &test) << std::endl;
std::cout << test;
}
Version 2 :
int value(int tab[], int &valeur)
{
for (int i = 0; i < 5; i++)
{
valeur += tab[i];
}
return valeur;
}
int main()
{
int test = 0;
int tab[10] = { 1,2,3,4,5};
std::cout << value(tab, test) << std::endl;
std::cout << test;
}

When the & character is part of a type declaration, it means that variable is a reference to another. So in the second function, int &valeur declares a variable named valeur that is a reference to an int. This example should help you understand:
#include <iostream>
int main() {
int a = 5;
int& b = a; // b is a reference to a
std::cout << a << '\n'; // outputs 5
std::cout << b << '\n'; // outputs 5
a = 7;
std::cout << a << '\n'; // outputs 7
std::cout << b << '\n'; // outputs 7
}
As a result, you can simply call your second function with value(tab, test) which passes the test variable by reference.

In the first example, value takes a pointer to int as second parameter. A pointer is used to save a memory address, so the function has to be called using the address operator (&), passing the address of test.
In the second example, value takes a non-const reference to int as second parameter, so you do not need to pass the memory address of test this time. What happens is almost equivalent to something like this:
int test = 0;
int& valeur = test;
So remember, the address operator:
int test;
std::cout << &test; // outputs address of "test" in memory
is not the same as a reference, which is part of the type of a variable:
int test;
int& valeur = test; // here, the type of "valeur" is "int&"

Related

c++ error: call to 'g' is ambiguous. By reference and regular function argument

In this code I want to call second function (with reference argument). How I can do this? This is even possible?
void g(int){ std::cout << 1; }
void g(int&){ std::cout << 2; }
int main() {
int i = 42;
g( i ); // want to output "2"
}
Do you want to have 1 when calling g(42) and 2 when calling g(i)?
Then you should change the prototype of the first function to get a const int &:
#include <iostream>
void g(const int&){ std::cout << 1; }
void g(int&){ std::cout << 2; }
int main() {
int i = 42;
g( i ); // want to output "2"
}
For g(i) the int & is a better fit than the const int &, so it will call the second.
You can't do it exactly like that. To overload functions, at least one of the arguments needs to be of a different type, or have a different number of arguments (see: https://www.cplusplus.com/doc/tutorial/functions2/). You could achieve something similiar, but rather unadvisable like this:
#include <iostream>
void g(int){ std::cout << 1; }
void g(long int&){ std::cout << 2; }
int main() {
int i = 42;
g(i); // outputs 1
long int i = 42;
g(i); // outputs 2
}
You can also get more information on function overloading here

What is the behavior of a scoped function that contains (xxx::*) [duplicate]

In my project, there are a few lines in a MyClass.h file
class MyClass{
public:
....
#ifndef __MAKECINT__
std::vector<Status_e(MyClass::*)(TupleInfo & info)> m_processObjects; //!
#endif
....
}
//The Status_e is an enum type
//The TupleInfo is a struct
I can't understand what the usage of this * in above code snippet. And in the MyClass.cxx file, the m_processObjects used as this:
for (unsigned int f = 0; f < m_processObjects.size(); ++f) {
status = (this->*m_processObjects[f])( m_tuples[i] );
if ( status == FAILURE ) {
return EL::StatusCode::FAILURE;
}
....
}
....
I have never heard about the usage like this->*blabla, but this code snippet works. So what it means?
::* denotes a Pointer to member.
With the surrounding code it's actually a Pointer to member function.
Status_e(MyClass::*)(TupleInfo & info)
is a member function of class MyClass, returning Status_e, and having one parameter TupleInfo&. (The argument name info is useless here but obviously silently ignored by the compiler.)
The other snippet in OP's question shows how to call it:
status = (this->*m_processObjects[f])(m_tuples[i]);
Storing a method pointer would look like this:
std::vector<Status_e(MyClass::*)(TupleInfo & info)> m_processObjects;
...
m_processObjects.push_back(&MyClass::aMethod);
Of course, the signature of MyClass::aMethod must match.
A simplified sample to demonstrate it:
#include <iostream>
#include <vector>
class Test {
private:
std::vector<int(Test::*)(const char*)> _tblTestFuncs;
public:
Test()
{
_tblTestFuncs.push_back(&Test::func1);
_tblTestFuncs.push_back(&Test::func2);
_tblTestFuncs.push_back(&Test::func3);
}
int func1(const char *caller) { std::cout << "Test::func1 called from '"<< caller << "': "; return 1; }
int func2(const char *caller) { std::cout << "Test::func2 called from '"<< caller << "': "; return 2; }
int func3(const char *caller) { std::cout << "Test::func3 called from '"<< caller << "': "; return 3; }
void call()
{
for (size_t i = 0, n = _tblTestFuncs.size(); i < n; ++i) {
int result = (this->*_tblTestFuncs[i])("Test::call()");
std::cout << "Return: " << result << '\n';
}
}
};
int main()
{
Test test;
// test method vector in main()
std::vector<int(Test::*)(const char*)> tblTestFuncs;
tblTestFuncs.push_back(&Test::func1);
tblTestFuncs.push_back(&Test::func2);
tblTestFuncs.push_back(&Test::func3);
for (size_t i = 0, n = tblTestFuncs.size(); i < n; ++i) {
int result = (test.*tblTestFuncs[i])("main()");
std::cout << "Return: " << result << '\n';
}
// test method vector in Test
test.call();
// done
return 0;
}
Output:
Test::func1 called from 'main()': Return: 1
Test::func2 called from 'main()': Return: 2
Test::func3 called from 'main()': Return: 3
Test::func1 called from 'Test::call()': Return: 1
Test::func2 called from 'Test::call()': Return: 2
Test::func3 called from 'Test::call()': Return: 3
Live Demo on coliru.com

What is the meaning of this star (*) symbol in C++? -- Pointer to member

In my project, there are a few lines in a MyClass.h file
class MyClass{
public:
....
#ifndef __MAKECINT__
std::vector<Status_e(MyClass::*)(TupleInfo & info)> m_processObjects; //!
#endif
....
}
//The Status_e is an enum type
//The TupleInfo is a struct
I can't understand what the usage of this * in above code snippet. And in the MyClass.cxx file, the m_processObjects used as this:
for (unsigned int f = 0; f < m_processObjects.size(); ++f) {
status = (this->*m_processObjects[f])( m_tuples[i] );
if ( status == FAILURE ) {
return EL::StatusCode::FAILURE;
}
....
}
....
I have never heard about the usage like this->*blabla, but this code snippet works. So what it means?
::* denotes a Pointer to member.
With the surrounding code it's actually a Pointer to member function.
Status_e(MyClass::*)(TupleInfo & info)
is a member function of class MyClass, returning Status_e, and having one parameter TupleInfo&. (The argument name info is useless here but obviously silently ignored by the compiler.)
The other snippet in OP's question shows how to call it:
status = (this->*m_processObjects[f])(m_tuples[i]);
Storing a method pointer would look like this:
std::vector<Status_e(MyClass::*)(TupleInfo & info)> m_processObjects;
...
m_processObjects.push_back(&MyClass::aMethod);
Of course, the signature of MyClass::aMethod must match.
A simplified sample to demonstrate it:
#include <iostream>
#include <vector>
class Test {
private:
std::vector<int(Test::*)(const char*)> _tblTestFuncs;
public:
Test()
{
_tblTestFuncs.push_back(&Test::func1);
_tblTestFuncs.push_back(&Test::func2);
_tblTestFuncs.push_back(&Test::func3);
}
int func1(const char *caller) { std::cout << "Test::func1 called from '"<< caller << "': "; return 1; }
int func2(const char *caller) { std::cout << "Test::func2 called from '"<< caller << "': "; return 2; }
int func3(const char *caller) { std::cout << "Test::func3 called from '"<< caller << "': "; return 3; }
void call()
{
for (size_t i = 0, n = _tblTestFuncs.size(); i < n; ++i) {
int result = (this->*_tblTestFuncs[i])("Test::call()");
std::cout << "Return: " << result << '\n';
}
}
};
int main()
{
Test test;
// test method vector in main()
std::vector<int(Test::*)(const char*)> tblTestFuncs;
tblTestFuncs.push_back(&Test::func1);
tblTestFuncs.push_back(&Test::func2);
tblTestFuncs.push_back(&Test::func3);
for (size_t i = 0, n = tblTestFuncs.size(); i < n; ++i) {
int result = (test.*tblTestFuncs[i])("main()");
std::cout << "Return: " << result << '\n';
}
// test method vector in Test
test.call();
// done
return 0;
}
Output:
Test::func1 called from 'main()': Return: 1
Test::func2 called from 'main()': Return: 2
Test::func3 called from 'main()': Return: 3
Test::func1 called from 'Test::call()': Return: 1
Test::func2 called from 'Test::call()': Return: 2
Test::func3 called from 'Test::call()': Return: 3
Live Demo on coliru.com

Simulating non-local (or free) variables in a locally defined struct

This question probably only makes sense for people with knowledge on programming languages supporting closures. If you don't, please do not comment "why would you like to do this?": there are tons of legitimate reasons to do that.
It is common in functional languages to define local functions that capture the already defined local variables. In C++, that would look like (but of course is illegal):
#include <iostream>
using namespace std;
int main()
{
int x = 0;
int f() { return x + 1; }
cout << f() << endl; // would print 1
x = 2;
cout << f() << endl; // would print 3
}
To allow this, C++11 introduces lambda functions, so it is actually possible to do it in a rather nice way (though, not as nice as it generally is in functional languages ;-) ):
#include <iostream>
using namespace std;
int main()
{
int x = 0;
auto f = [&] () { return x + 1; };
cout << f() << endl; // actually compiles and prints 1
x = 2;
cout << f() << endl; // actually compiles and prints 3
}
My question is: now that it is possible to automatically capture free variables by reference for functions, wouldn't that be nice to be possible to do for locally defined structs? Ideally, I would love to be able to write:
int main()
{
int x = 0;
struct A
{
int y;
A(int y) : y(y) {}
int f() { return x + y; };
};
A a1(1);
A a2(2);
cout << a1.f() << endl; // would print 1
cout << a2.f() << endl; // would print 2
x = 2;
cout << a1.f() << endl; // would print 3
cout << a2.f() << endl; // would print 4
}
The only workaround I've found is to manually pass as argument to the constructor all the non-local (free) variables, which is a bit of a pain when there are plenty of them:
#include <iostream>
using namespace std;
int main()
{
int x = 0;
struct A
{
// meaningful members
int y;
int f() { return x + y; };
// free variables
int & x;
// Constructor
A(
// meaningful arguments
int y,
// capturing free variables
int & x
) : y(y), x(x) {}
};
A a1(1, x);
A a2(2, x);
cout << a1.f() << endl; // prints 1
cout << a2.f() << endl; // prints 2
x = 2;
cout << a1.f() << endl; // prints 3
cout << a2.f() << endl; // prints 4
}
Do you know of any other workaround that would avoid manually passing as argument all free variables, or do you know if these kind of "environment-aware" locally-defined structs are considered for future extensions of C++? (i.e., C++1y?)
What you ask for is not available, but you can get similar results by combining functions with a combination of lambdas and binders:
auto lambda = [](int i) { return x+i; };
auto a1 = std::bind(lambda,1);
auto a2 = std::bind(lambda,2);
Depending on the amount and shape of changes, you could invert the solution and have a struct that takes the lambda with the capture and then adds it's own logic.
I don't find this particularly beautiful, and I'm not entirely sure it's compliant, but neither g++ nor clang++ complains about this:
#include <iostream>
int main()
{
int x = 1;
auto l = [&](int p){
auto ll0 = [&, p]{ return p + x + 5; };
auto ll1 = [&, p]{ return p + x * 2; };
struct
{
decltype(ll0) l0;
decltype(ll1) l1;
} ret{ll0, ll1};
return ret;
};
std::cout << l(42).l0() << '\n';
auto lo = l(21);
std::cout << lo.l1() << '\n';
}
I think the creation of the unnamed struct could possibly be automated by a macro.
The lambda expressions of C++ are the capturing mechanism and inline object literals of a sort. Depending on your exact purpose, they may be more convenient than a local struct definition.
As a motivating example, consider the following:
// environment
int offset = 42;
struct local_type {
// capture environment 'by-hand'
int offset;
// purpose of the local type is to expose two overloads
int operator()(int x) const
{ return x + offset; }
double operator()(double x) const
{ return x + offset; }
} f { offset };
You can turn this on its head by doing:
int offset = 42;
auto f = make_overload([=](int x) { return offset + x; },
[=](double x) { return offset + x; });
The lambda expressions take care of capturing, the make_overload combinator takes care of building the desired object -- here, one that has an overloaded operator(). (It would be implemented best by making use of inheritance.)
This approach makes sense if you know that you'll (re)use make_overload from various places. For one-time, special uses there's no avoiding writing a specialty type, whether local or not.

cyclic negative number generation in C++

I have requirement as follows.
I have to generate increment negative numbers from -1 to -100 which is used a unique id for a request. Like it should be like this: -1, -2, -3, ...-100, -1, -2, and so on. How can I do this effectively? I am not supposed to use Boost. C++ STL is fine. I prefer to write simple function like int GetNextID() and it should generate ID. Request sample program on how to do this effectively?
Thanks for your time and help
int ID = -1;
auto getnext = [=] mutable {
if (ID == -100) ID = -1;
return ID--;
};
Fairly basic stuff here, really. If you have to ask somebody on the Interwebs to write this program for you, you should really consider finding some educational material in C++.
I love the functor solution:
template <int limit> class NegativeNumber
{
public:
NegativeNumber() : current(0) {};
int operator()()
{
return -(1 + (current++ % limit));
};
private:
int current;
};
Then, you can define any generator with any limit and use it:
NegativeNumber<5> five;
NegativeNumber<2> two;
for (int x = 0; x < 20; ++x)
std::cout << "limit five: " << five() << "\tlimit two: " << two() << '\n';
You can also pass the generator as parameter to another function, with each funtor with its own state:
void f5(NegativeNumber<5> &n)
{
std::cout << "limit five: " << n() << '\n';
}
void f2(NegativeNumber<2> &n)
{
std::cout << "limit two: " << n() << '\n';
}
f5(five);
f2(two);
If you don't like the template solution to declare the limit, there's also the no-template version:
class NegativeNumberNoTemplate
{
public:
NegativeNumberNoTemplate(int limit) : m_limit(limit), current(0) {};
int operator()()
{
return -(1 + (current++ % m_limit));
};
private:
const int m_limit;
int current;
};
Using as argument to a function works in the same way, and it's internal state is transfered as well:
void f(NegativeNumberNoTemplate &n)
{
std::cout << "no template: " << n() << '\n';
}
NegativeNumberNoTemplate notemplate(3);
f(notemplate);
I hope you don't want to use it with threading, they're not thread safe ;)
Here you have all the examples; hope it helps.
Something like.... (haven't compiled)
class myClass
{
int number = 0;
int GetValue ()
{
return - (number = ((number+1) % 101))
}
}
Even a simple problem like this could lead you to several approximations, both in the algorithmic solution and in the concrete usage of the programming language.
This was my first solution using C++03. I preferred to switch the sign after computing the value.
#include <iostream>
int GetNextID() {
// This variable is private to this function. Be careful of not calling it
// from multiple threads!
static int current_value = 0;
const int MAX_CYCLE_VALUE = 100;
return - (current_value++ % MAX_CYCLE_VALUE) - 1;
}
int main()
{
const int TOTAL_GETS = 500;
for (int i = 0; i < TOTAL_GETS; ++i)
std::cout << GetNextID() << std::endl;
}
A different solution taking into account that the integer modulo in C++ takes the sign of the dividend (!) as commented in the Wikipedia
#include <iostream>
int GetNextID() {
// This variable is private to this function. Be careful of not calling it
// from multiple threads!
static int current_value = 0;
const int MAX_CYCLE_VALUE = 10;
return (current_value-- % MAX_CYCLE_VALUE) - 1;
}
int main()
{
const int TOTAL_GETS = 50;
for (int i = 0; i < TOTAL_GETS; ++i)
std::cout << GetNextID() << std::endl;
}