Domanda

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)

È stato utile?

Soluzione

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.

Altri suggerimenti

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top