Accessing the variable inside anonymous namespace (c++) - c++

I have following code and I don't know how can I access the x inside the anonymous namespace in this setting. Please tell me how?
#include <iostream>
int x = 10;
namespace
{
int x = 20;
}
int main(int x, char* y[])
{
{
int x = 30; // most recently defined
std::cout << x << std::endl; // 30, local
std::cout << ::x << std::endl; // 10, global
// how can I access the x inside the anonymous namespace?
}
return 0;
}

You can't!
You cannot access the namespace's members by its name, because it doesn't have one.
It's anonymous.
You can only access those members by virtue of their having been pulled into scope already.

You'll have to access it from a function within the anonymous same scope:
#include <iostream>
int x = 10;
namespace
{
int x = 20;
int X() { return x; }
}
int main(int x, char* y[])
{
{
int x = 30; // most recently defined
std::cout << x << std::endl; // 30, local
std::cout << ::x << std::endl; // 10, global
std::cout << X() << std::endl; // 20, anonymous
// how can I access the x inside the anonymous namespace?
}
return 0;
}

Related

Affecting a function to another function in c++

So there's this code am trying to understand:
#include <iostream>
using namespace std;
int x = -2;
int h(int &x) {
x = 2 * x;
return x;
}
int g(int f) { return x; }
int &f(int &x) {
x += ::x;
return x;
}
int main() {
int x = 6;
f(::x) = h(x);
cout << f(x) << endl;
cout << g(x) << endl;
cout << h(x) << endl;
return 0;
}
Output:
24
12
48
I understood the function of the scope resolution operator (::), which is to use the global int x, but the part that i don't understand is this part: f(::x) = h(x); and this one: int g(int f){return x;}
So what am trying to understand is what happens step by step when these instructions get executed.
The line
f(::x) = h(x);
is equivalent to
operator=(f(::x), h(x));
First, one of the functions f or h are called and the returned value is passed to operator=. Then the other function is called and the returned value is passed to operator=. The order is irrelevant because in either case f changes the value of global x to -4 and returns a reference to it and h changes local x (local in main) to 12 and returns its value. Then the value 12 is assigned to global x.
The line
int g(int f) { return x; }
defines a function that returns the value of global x.
Maybe using different variable names helps understanding:
#include <iostream>
using namespace std;
int globalX = -2;
int h(int &hX) {
hX = 2 * hX;
return hX;
}
int g(int f) { return globalX; } // f is unused
int &f(int &fX) {
fX += ::globalX;
return fX;
}
int main() {
int mainX = 6;
f(::globalX) = h(mainX);
cout << f(mainX) << endl;
cout << g(mainX) << endl;
cout << h(mainX) << endl;
return 0;
}

Access a member in a struct via a variable in C++

I have a struct with two members, for example:
struct DataSet {
int x;
int y;
};
..., and i have to access those in a method, but only one at a time, for example:
void foo(StructMember dsm) { // ("StructMember" does not exist)
DataSet ds;
ds.x = 4;
ds.y = 6;
std::cout << ds.dsm * ds.dsm << std::endl;
}
foo(x);
foo(y);
Output i wish to have:
16
36
What should I do when I have to solve a problem like this? Is there a data type which can access a member?
Yes, you can use a pointer-to-member. The syntax for the type is TypeOfMember TypeOfStruct::*, and to access you do struct_variable.*pointer_variable
using StructMember = int DataSet::*; // Pointer to a member of `DataSet` of type `int`
void foo(StructMember dsm) {
DataSet ds;
ds.x = 4;
ds.y = 6;
std::cout << ds.*dsm * ds.*dsm << std::endl;
}
int main() {
foo(&DataSet::x);
foo(&DataSet::y);
}

C++: static variables not changing with static set() function

After reading StackOverflow's discussions and implementing some advices, I have these pieces of code intended just to test the behavior of static members of a class.
Here is the header, which has the class declaration:
class OurClass
{
private:
static int x, y;
public:
static void setVals(int valx, int valy);
static int getValx();
static int getValy();
static void initialize();
};
And here is the cpp file, which has the definition of these members as well as the main() function:
#include <iostream>
#include "OurClass.hpp"
using namespace std;
void OurClass::initialize()
{
static int x = 0;
static int y = 0;
}
void OurClass::setVals(int valx, int valy)
{
static int x = valx;
static int y = valy;
}
int OurClass::getValx()
{
static int x;
return x;
}
int OurClass::getValy()
{
static int y;
return y;
}
int main(void)
{
OurClass::inicializa();
cout << "Provide x and y..." << endl;
OurClass::setVals(cin.get(), cin.get());
cout << "Value of x: " << OurClass::getValx() << endl;
cout << "Value of y: " << OurClass::getValy() << endl;
return 0;
}
So, assuming that a static variable exists for the class, and that static functions only access static variables, I was expecting that x and y would have the values that we read from the keyboard with the setVals() call in main(). But when printing their values in the couts, they still have the value we assigned in the initialize() function (which BTW was another suggestion I got here, that is, initialize a static variable in a method).
I am also unable to refer directly to the variables by OurClass::x or y even if I make them public.
Do you guys know why?
First you need to access your local class's static variable instead declaring new method local variables in each method. Check below.
class Out {
private:
static int x, y;
public:
void set(int x, int y);
int getSum();
};
int Out::x = 0;
int Out::y = 0;
void Out::set(int x, int y) {
Out::x = x;
Out::y = y;
}
int Out::getSum() {
return Out::x + Out::y;
}
Instead of setting values of existing variables this code creates new local static variables. Fix:
void OurClass::initialize()
{
x = 0;
y = 0;
}
void OurClass::setVals(int valx, int valy)
{
x = valx;
y = valy;
}
int OurClass::getValx()
{
return x;
}
int OurClass::getValy()
{
return y;
}
And add the definitions of those static variables in a .cc file (not header):
int OurClass::x;
int OurClass::y;

what does a ampersand before double colon mean in c++?

I found this usage in the following code generated by google's protobuf.
inline void Datum::set_data(const void* value, size_t size) {
set_has_data();
//over here.
if (data_ == &::google::protobuf::internal::kEmptyString) {
data_ = new ::std::string;
}
data_->assign(reinterpret_cast<const char*>(value), size);
}
Thank you:-)!
It's two totally unrelated things, perhaps better thought of as
&(::google::protobuf::internal::kEmptyString)
& just means the address-of operator, exactly the same as if you'd done:
int xyzzy = 7;
int *pointer_to_xyzzy = &xyzzy;
The ::, on the other hand, is the global namespace specifier, to ensure you don't start looking in your current namespace.
For example, the following program:
#include <iostream>
int x = 7;
namespace xyzzy {
int x = 42;
int getxa() { return ::x; }
int getxb() { return x; }
}
int main() {
std::cout << xyzzy::getxa() << '\n';
std::cout << xyzzy::getxb() << '\n';
return 0;
}
outputs 7 followed by 42 since the getxa() function uses the global namespace specifier rather than the xyzzy one.

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.