Home > Net >  How to define namespace name same as return type of function in that namespace?
How to define namespace name same as return type of function in that namespace?

Time:08-30

I have something like this in my header:

namespace Utils
{
    namespace Klass
    {
        Klass fromObject(Object object)
        {
            if (something) {
                return a;
            } else if (something2) {
                Klass b = Klass::initialise();
                return b;
            // ...
            } else {
                return Klass();
            {
        }

        Klass fromString() { ... }
        Klass fromInt() { ... }
        // ...
    }
}

I want to be able to call this like this:

Klass k1 = Utils::Klass::fromObject(obj);
Klass k2 = Utils::Klass::fromString(str);

Problem I have, when I write it this way, is that I get error "Must use 'class' tag to refer to type 'Klass' in this scope".

Error is fixed when I add the keyword class:

namespace Klass
{
    class Klass fromObject(Object object)
    {
    ...
        } else if (something2) {
            class Klass b = Klass::initialise();
            return b;
    ...

But I don't know how to fix this in the else of this function. I cannot write return class Klass();.

Is it even possible to do something like this in C ? What I am trying to do is to group my utility functions according to a type they return.

CodePudding user response:

I think the following should be correct inside the block scope of the function:

using Klass = class Klass;
Klass b = Klass::initialise();
//...

After the using type alias Klass should always refer to this alias, not the namespace.

That this is unlikely to be a good idea though is already discussed in the comments under the question.

CodePudding user response:

for return class Klass();


you can simply write

return {};

as long as Klass doesn't overload for initializer_list (or the semantic doesn't change)


or you can (fully) qualify the name

return ::whatever::ns::Klass();



generally, you can introduce alias for internal use

namespace Utils
{
    namespace Klass
    {
        using the_Klass = ::Klass;
        the_Klass fromObject(Object object)
        {
            return the_Klass();
        }
    }
}
  • Related