This question already has answers here:
Is it possible to detect namespace membership in C++?
(2 answers)
Closed 9 years ago.
I'm trying to write a log library which would use an external tool
To make the library more natural to use, i would like to be able to detect the namespace in which cout is used.
concretly the result should be used like this
namespace A
{
void foo()
{
cout << "Something went very wrong" << endl;
}
}
namespace B
{
void bar()
{
cout << "C should equal 3" << endl;
}
}
int main()
{
B::bar();
A::foo();
}
and the resulting output should look like this
MODULE::B : C should equal 3
MODULE::A : Something went very wrong
I already use std::streambuf to add certain keywords to the output of cout, all i need to be able to do is specify which streambuf to use in which namespace.
How do i achieve this?
Also the library i'm making is to be integrated in a project with multiple namespaces which making heavy uses of the using namespace declaration. I would need a solution which will not require to remove these declarations.
edit1: i don't care having to specify by hand which namespace is associated with which string or adding objects to any of the used namespaces (except std of course)
How about creating your custom logger stream? That way the user can specify the component that failed, like so:
namespace A {
void foo()
{
log("A") << "Something went very wrong" << endl;
}
}
namespace B {
void bar()
{
log("B") << "C should equal 3" << endl;
}
}
int main()
{
B::bar();
A::foo();
}
Perhaps less automagical, but __FILE__ macro could also give some information.
This is not possible in the language. If you are using Clang you could recompile Clang to perform such a task for you.
you may try to inject function like std::string namespace_name() in every namespace you want to show up, and then call std::cout << namespace_name() would lead most inner namespace name output
Related
void fun(){
std::cout << "hello" << std::endl;
}
namespace enc{
using ::fun;
}
This code above gives no error. I want to understand what's going on here.
What does using ::fun; mean?
Breaking this down we have:
void fun() is a function that does not return a value (essentially nothing).
:: is a scope resolution operator. For example, cout and cin are defined in the std namespace. To qualify their names without using the using declaration we have to qualify them with std::cout and std::cin
To answer the main question, however:
using ::fun; is called a using declaration. A using declaration means that you can introduces namespace members into other namespaces, etc. This means that fun will now be visible as ::enc::fun;
For example:
void fun() {
std::cout << "hello" << std::endl;
}
namespace enc {
using ::fun;
}
void Reallyfun()
{
enc::fun(); // Which calls ::fun
}
using a synonymous declaration introduces a name from one declarative region into another. In this case, the name fun is introduced into the namespace ::enc and it is synonymous with ::fun.
I've been trying to convince myself that that objects of the same type have access to each others private data members. I wrote some code that I thought would help me better understand what is going on, but now I am getting an error from XCODE7 (just 1), that says that I am using the undeclared identifier "combination."
If someone could help me understand where I have gone awry with my code, I would love to learn.
My code should simply print false, if running correctly.
#include <iostream>
using std::cout;
using std::endl;
class Shared {
public:
bool combination(Shared& a, Shared& b);
private:
int useless{ 0 };
int limitless{ 1 };
};
bool Shared::combination(Shared& a,Shared& b){
return (a.useless > b.limitless);
}
int main() {
Shared sharedObj1;
Shared sharedObj2;
cout << combination(sharedObj1, sharedObj2) << endl;
return 0;
}
combination is a member function of the class Shared. Therefore, it can only be called on an instance of Shared. When you are calling combination, you are not specifying which object you are calling it one:
cout << combination(sharedObj1, sharedObj2) << endl;
^^^
Instance?
The compiler complains because it thinks you want to call a function called combination, but there is none.
So, you'll have to specify an instance:
cout << sharedObj1.combination(sharedObj1, sharedObj2) << endl;
In this case however, it doesn't matter on which instance it is being called on, so you should make combination static, so you can do
cout << Shared::combination(sharedObj1, sharedObj2) << endl;
I'm currently trying to create a basic quiz game in C++.
The following code throws an error when I try to run it, it works if I don't use answer("answer") in the main class and instead substitute it with the actual code.
I wanted to "nest" (I don't know the technical term) some of the code so that I did not have to keep writing it out every time, as you can see i was hoping to write any question followed by answer("answer").
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "QUIZ C++ EDITION!\n";
cout << "Question 1:\n";
cout << "What is the colour you get when you mix red and yellow?\n\n";
question("Orange");
system("PAUSE");
}
void question(string answer) {
string input;
getline(cin, input);
if (input == answer) {
cout << "\nCorrectimundo!\n";
}
else
{
cout << "\nWrongimundo.\n";
}
return;
}
I have a feeling it's a case of wrong syntax but the IDE is not showing me where the error is unfortunately, it only happens when I run the program.
It looks like you are trying to make a function. Can I help?
– Clippy (1997-2007 RIP)
Two ways to do this. One is to forward declare question ahead of its first use.
void question(string answer);
int main()
{
...
question("Orange")
...
}
void question(string answer)
{ ... }
A forward declaration is a promise to the compiler that question will be fully defined somewhere else, maybe later in this file, maybe in another file, maybe in a library. But it must be defined somewhere or the program will compile, but it will not link.
And the other is to fully define question ahead of it's first use.
void question(string answer)
{ ... }
int main()
{
...
question("Orange")
...
}
I prefer the second approach because there is no possibility of falling into a trap like this:
void question(int answer);
int main()
{
...
question(42)
...
}
void question(string answer)
{ ... }
and getting a linker error from changing the forward declaration of question and forgetting to change the definition.
You need to provide a declaration of the function question before you can use it in main. Add
void question(string answer);
before the definition of main.
In C++ you must declare a function before you can use it (note, definition is also a declaration), but there is no mention of function question before line
question("Orange");
when it is actually trying to get called. Add a declaration:
void question(string answer);
int main()
{
// the rest of code ...
You forgot to declare your function , you can either declare it before main or just write the whole function before main.
You need to add before your main:
void question(string value);
Suppose I have two overloaded functions :
fun1(int)
fun1()
In this case how can I use #pragma startup directive to start my program's execution with fun1(int) ?
The syntax only contains the function name :
#pragma startup fun1 100
Is there any way by which I can make a choice between these two functions?
UPDATE:
compiler- turbo c/c++ 3.1 (sorry for an old compiler )
It is a Borland specific directive, still documented as well. It just lets you specify a function that runs before the main() function is entered. You normally use it for an initialization function. It is a small band-aid for the infamous "static initialization order fiasco" that C and C++ implementations suffer from. Not so sure it stops the bleeding, having to pick the priority number ought to get impractical when the program gets large.
Anyhoo, nothing you ought to use as a replacement of main(). Although I'd suspect you could make it work as long as you don't return from the function and call exit(). You can't use an argument of course, there's nothing meaningful that the CRT can pass. So overloads can't work either. Stick with main().
#joey-rohan, I dont have borland but have tried to provide some code below to demonstrate:
#pragma start requires a non parameterised function, the number after the function call is the priority of the function where 0 is the highest and 255 the lowest. The function should ideally (varies in some compilers) be defined prior to the #pragma call. Source: embarcadero
I have done a bit of scouting about and think that the solution to your dilemma would be to use a mixture of #define and #pragma to achieve what you would like to do. For example something like:
#include <iostream>
#define myvalue 100
#define usemyvalue 0
void fun1(int passedInValue)
{
// carry out function here
std::cout << "I was passed the value:" << passedInValue << std::endl;
}
void fun1(void)
{
std::cout << "in fun1(void)\n";
std::cout << "Use my value = " << usemyvalue<< std::endl;
if (usemyvalue==1)
{
std::cout << "Using fun1(int) with a value!\n";
fun1((int)myvalue); // remember to cast as an int here
}
else
{
//normal fun1()code here
std::cout << "No var passed!\n";
std::cout << "Running standard non parametrised code!\n";
}
}
#pragma start fun1 10
int main()
{
std::cout << "Hello World\n";
return 0;
}
I know this is not as elegant as I would wish, therefore its probably not as elegant as you would like either, however it does allow for the functionality you need, with minimal modification. Unfortunately i only have GCC available to test against on this machine and it does not seem to support #pragma start it does however support a differing way of achieving the same (as shown on C Language Constructors and Destructors with GCC
so here is some code for GCC which I could test to let you see how to achieve what you are asking (because I would hate to pst a methodology that cannot be proven):
#include <iostream>
#define myvalue 100
#define usemyvalue 1 // this is the control switch to determine which to use,
// if the value is 1 then will pass a variable, otherwise will use
// the fun1(void) function
void fun1 (void) __attribute__((constructor));
void fun1(int passedInValue)
{
// carry out function here
std::cout << "I was passed the value:" << passedInValue << std::endl;
}
void fun1(void)
{
std::cout << "in fun1(void)\n";
std::cout << "Use my value = " << usemyvalue<< std::endl;
if (usemyvalue==1)
{
std::cout << "Using fun1(int) with a value!\n";
fun1((int)myvalue); // remember to cast as an int here
}
else
{
//normal fun1()code here
std::cout << "No var passed!\n";
std::cout << "Running standard non parametrised code!\n";
}
}
#pragma startup fun1
int main()
{
std::cout << "now running main function.\n";
std::cout << "Hello World\n";
return 0;
}
I suspect that the second method would also work with Borlands compiler but without access to it I cannot swear to that.
Hope this helps!
I can neither find any documentation on your compiler, nor use the compiler itself to check my guess. But from what I remember, #pragma startup takes function without arguments and returning void.
I would further guess that your code is not going to work if you leave only function taking int argument.
Disregarding that, I think it's not possible to pass an argument to function called in such a way.
As a solution I would propose you creating wrapper function, calling whatever function you would like with necessary arguments, like:
void start()
{
#pragma startup start
fun1( global_var_name );
}
I'm not exactly sure I understand the restrictions, but how about simply defining another function with a different name to forward to the function you want?
void fun2() { fun1(42); }
#pragma startup fun2 100
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have a problem with, to me, unusual homework:
Dont modify the main function but change the program that it prints as
output:
Monday
is the first day
of the week
And heres the given code:
int main()
{
cout << "is the first day\n";
}
Any help will be appreciated :)
What he's undoubtedly interested in your demonstrating is the fact that a global object (defined in the same translation unit) will be constructed before main is entered, and destroyed after main exits.
Be aware that when such a global object is being constructed, std::cout may not exist yet (and when it's being destroyed, std::cout may no longer exist), so any printing you do just about has to be via C functions like printf.
Another atrocious idea, just for the fun of it:
#include <iostream>
using namespace std;
#define main real_main
int main()
{
cout << "is the first day\n";
}
#undef main
int main()
{
cout << "Monday\n";
int res = real_main();
cout << "of the week\n";
return res;
}
Another version which does not rely on preprocessor foo would be to use global static object construction and destruction. This is safe, since apparently the standard guarantees that std::cout (and friends) is initialized and destroyed before/after all user code:
#include <iostream>
using namespace std;
struct Homework
{
Homework()
{
cout << "Monday\n";
}
~Homework()
{
cout << "of the week\n";
}
} hw;
int main()
{
cout << "is the first day\n";
}
Seems like a poor homework question. I can see no way to print other outputs without modifying the main method - unless you created another main method to override this?! The code provide is wrong as well - it should return 0 as main is expected to return an integer.
What about this?
#include <iostream>
#include <cstdlib>
using namespace std;
struct Foo
{
Foo()
{
cout << "Monday\nis the first day\nof the week\n";
exit(0);
}
} X;
int main()
{
cout << "is the first day\n";
}
Update
Ok, you may use name 'cout' in main func like some object not from iostream:
#include <iostream>
#include <string>
class Foo
{
public:
void operator <<( const std::string & s )
{
std::cout << "Monday\n" << s << "of the week";
}
} cout;
int main()
{
cout << "is the first day\n";
}
There are at least a couple of ways you can do this.
You can replace the meaning of cout.
You can make things happen before and after main is called.
Redefining cout:
#include <iostream>
class MyCout {};
void operator<<(MyCout& myCout, const char* message) {
std::cout << "Monday\n";
std::cout << message;
std::cout << "of the week\n";
}
MyCout cout;
int main()
{
cout << "is the first day\n";
}
To making things happen before and after main, you can create a static object. Their constructor is called before main, and the destructor afterwards:
#include <iostream>
class PrintExtras {
public:
PrintExtras() {
std::cout << "Monday\n";
}
~PrintExtras() {
std::cout << "of the week\n";
}
};
PrintExtras printExtras;
using std::cout;
int main()
{
cout << "is the first day\n";
}
I think you should make an operator overload for the output stream.
Think of things that happen before entry into main or after exit from main.
Early in a program you typically have initialization, at the end its counterpart.
What is the C++ idiom for those things?
How can you make those happen outside the body of main()?
What do you know about objects defined at namespace scope?
It really depends on where you are with your course, if you know about these things.
Alternative: The object used in main is only std::cout if you bring that name into the global namespace. Objects in namespaces other than ::std can also bear that name.