How to avoid splitting namespace scope?

J

Jayden Shui

Hello All,

I give every class a tag by specialize the following template
function:

template<class T>
std::string Tag();

However, when working on a class in a namespace such as

namespace S
{
class A { /*codes for A*/ };

template<>
std::string Tag<A>()
{
return "A";
}

// other codes
}

The compiler give an error. I have to specialize it in global scope
like

namespace S
{
class A { /*codes for A*/ };
}

template<>
std::string Tag<S::A>()
{
return "A";
}

namespace S
{
// other codes
}

I don't want split the namespace scope by the tag specialization.
Anyway I can make it work without the splitting?

Thank you very much for your kind help!

Best regards,

Jayden
 
L

laird

If all you want is a string describing the class, have you considered using the typeid operator?

S::A a;
cout << typeid(a).name() << endl;

or create a single global Tag function template:

template<class T> string Tag(T& t) { return typeid(a).name(); }

Laird Breyer.
 
J

Jayden Shui

If all you want is a string describing the class, have you considered using the typeid operator?

S::A a;
cout << typeid(a).name() << endl;

or create a single global Tag function template:

template<class T> string Tag(T& t) { return typeid(a).name(); }

Laird Breyer.

Thanks. But I'd like the tag more readable. Any other way?

Best regards,

Jayden
 
B

Bo Persson

Jayden said:
Hello All,

I give every class a tag by specialize the following template
function:

template<class T>
std::string Tag();

However, when working on a class in a namespace such as

namespace S
{
class A { /*codes for A*/ };

template<>
std::string Tag<A>()
{
return "A";
}

// other codes
}

The compiler give an error. I have to specialize it in global scope
like

namespace S
{
class A { /*codes for A*/ };
}

template<>
std::string Tag<S::A>()
{
return "A";
}

namespace S
{
// other codes
}

I don't want split the namespace scope by the tag specialization.
Anyway I can make it work without the splitting?

No really. You cannot specialize a template from one namespace inside
another namespace.


Bo Persson
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top