473,840 Members | 1,444 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Convert template argument to string

Hi there

I'm looking for a template class that converts the template argument to a
string, so something like the following should work:

Convert<float>: :Get() == "float";
Convert<3>::Get () == "3";
Convert<HelloWo rld>::Get() == "HelloWorld ";

The reason I need this is that in our design every class of a certain
hierarchy has a class name that must be unique. So far I could not find a
solution for template classes.

Thanks for your ideas
Marco

Oct 16 '08 #1
9 17592
Marco Nef wrote:
Hi there

I'm looking for a template class that converts the template argument to
a string, so something like the following should work:

Convert<float>: :Get() == "float";
Convert<3>::Get () == "3";
Convert<HelloWo rld>::Get() == "HelloWorld ";

The reason I need this is that in our design every class of a certain
hierarchy has a class name that must be unique. So far I could not find
a solution for template classes.
You have to provide one or use typeid.

--
Ian Collins
Oct 16 '08 #2
Marco Nef schrieb:
I'm looking for a template class that converts the template argument to
a string, so something like the following should work:

Convert<float>: :Get() == "float";
Convert<3>::Get () == "3";
Convert<HelloWo rld>::Get() == "HelloWorld ";

The reason I need this is that in our design every class of a certain
hierarchy has a class name that must be unique. So far I could not find
a solution for template classes.
Solution 1:

Use RTTI. With typeid(...).nam e() you will get a unique name. However,
this name is compiler dependant and may not look pretty at all. If you
don't care about that, it is fine. (Of course, the lookup is done at
runtime.)
Solution 2:

The good old macros.
#define TOSTRING(x) #x
will convert anything you pass to it into a string, e.g. TOSTRING(float)
will evaluate to "float" at compile time. But you will not manage to
take care of namespaces this way. The macro will always return the
string as it is - with or w/o namespace prefix.
Marcel
Oct 16 '08 #3
On Oct 16, 7:43*am, "Marco Nef" <maill...@shima .chwrote:
I'm looking for a template class that converts the template argument to a
string, so something like the following should work:

Convert<float>: :Get() == "float";
Convert<3>::Get () == "3";
Convert<HelloWo rld>::Get() == "HelloWorld ";

The reason I need this is that in our design every class of a certain
hierarchy has a class name that must be unique. So far I could not find a
solution for template classes.
What do you need those names for? Why do you want for it to work with
values as well as with types?

If typeid(X).name( ) is not sufficient for you (not portable, may be
not human readable), you'll have to provide a string for every class
yourself.

--
Max
Oct 16 '08 #4
I'm looking for a template class that converts the template argument to
a
string, so something like the following should work:

Convert<float>: :Get() == "float";
Convert<3>::Get () == "3";
Convert<HelloWo rld>::Get() == "HelloWorld ";

The reason I need this is that in our design every class of a certain
hierarchy has a class name that must be unique. So far I could not find
a
solution for template classes.

What do you need those names for? Why do you want for it to work with
values as well as with types?

If typeid(X).name( ) is not sufficient for you (not portable, may be
not human readable), you'll have to provide a string for every class
yourself.

--
Max
Thanks for your replies. I know about typeid and it is not sufficient as
"typeid->name" by the standard is not persistent and not even unique. The
macro "TOSTRING(x ) #x" does not work because it is evaluated before the
template process works. This means that "Convert<float> ::Get()" returns
"Type" if Type is the name of the template argument.

Another solution would be the following:

template<typena me Typestruct Convert
{
const String &GetName(VOI D) const { return Type::GetName() ; }
};
template<struct Convert<float>
{
const String &GetName(VOI D) const { return "float"; }
};
template<struct Convert<int>
{
const String &GetName(VOI D) const { return "int"; }
};

and so on...

So any classes provided as template argument need to implement GetName(),
for the base types there are specializations . This works, but I don't really
like it.

I would love a struct like:

template<typena me Typestruct Convert
{
const String &GetName(VOI D) const { return XXXXXX; }
};

where XXXXXX is the question of this task :-)

Marco

Oct 16 '08 #5
On Oct 16, 9:57*am, "Marco Nef" <maill...@shima .chwrote:
I'm looking for a template class that converts the template argument to
a
string, so something like the following should work:
Convert<float>: :Get() == "float";
Convert<3>::Get () == "3";
Convert<HelloWo rld>::Get() == "HelloWorld ";
The reason I need this is that in our design every class of a certain
hierarchy has a class name that must be unique. So far I could not find
a
solution for template classes.
What do you need those names for? Why do you want for it to work with
values as well as with types?
If typeid(X).name( ) is not sufficient for you (not portable, may be
not human readable), you'll have to provide a string for every class
yourself.

Thanks for your replies. I know about typeid and it is not sufficient as
"typeid->name" by the standard is not persistent and not even unique. The
macro "TOSTRING(x ) #x" does not work because it is evaluated before the
template process works. This means that "Convert<float> ::Get()" returns
"Type" if Type is the name of the template argument.

Another solution would be the following:

template<typena me Typestruct Convert
{
* * const String &GetName(VOI D) const { return Type::GetName() ; }};

template<struct Convert<float>
{
* * const String &GetName(VOI D) const { return "float"; }};

template<struct Convert<int>
{
* * const String &GetName(VOI D) const { return "int"; }

};

and so on...
Please note, that in C++ you don't need (void) for functions with no
arguments. () is sufficient.

These GetName() functions return a reference to a non-existent
constant String, which is a programming error.
So any classes provided as template argument need to implement GetName(),
for the base types there are specializations . This works, but I don't really
like it.
You don't really need to provide a name for each specialisation,
because it can be generated in a generic fashion. Here is an example:

#include <string>
#include <iostream>

template<class T>
struct TypeName
{
static std::string get() { return T::typeName(); }
};

// add more specialisations for the build-in types
template<std::s tring TypeName<int>:: get() { return "int"; }

struct A
{
static std::string typeName() { return "A"; }
};

template<class T>
struct B
{
static std::string typeName() { return "B<" +
TypeName<T>::ge t() + ">"; }
};

int main()
{
std::cout << TypeName<int>:: get() << '\n';
std::cout << TypeName<A>::ge t() << '\n';
std::cout << TypeName<B<int: :get() << '\n';
std::cout << TypeName<B<A::g et() << '\n';
std::cout << TypeName<B<B<B< int ::get() << '\n';
}

Output:

int
A
B<int>
B<A>
B<B<B<int>>>

--
Max

Oct 16 '08 #6
On Oct 16, 9:28 am, Marcel Müller <news.5.ma...@s pamgourmet.com>
wrote:
Marco Nef schrieb:
I'm looking for a template class that converts the template
argument to a string, so something like the following should
work:
Convert<float>: :Get() == "float";
Convert<3>::Get () == "3";
Convert<HelloWo rld>::Get() == "HelloWorld ";
The reason I need this is that in our design every class of
a certain hierarchy has a class name that must be unique. So
far I could not find a solution for template classes.
Solution 1:
Use RTTI. With typeid(...).nam e() you will get a unique name.
Maybe. I've never found a compiler where the name was
guaranteed unique, or was even unique in practice. If he's
using it in a template, however, it might be alright; templates
arguments must have external linkage, and most compilers do seem
to generate unique names for all types with external linkage.
Solution 2:

The good old macros.
#define TOSTRING(x) #x
will convert anything you pass to it into a string, e.g.
TOSTRING(float) will evaluate to "float" at compile time. But
you will not manage to take care of namespaces this way. The
macro will always return the string as it is - with or w/o
namespace prefix.
And within a template, TOSTRING(T) will result in "T",
regardless of what T actually means in the instantiation.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Oct 16 '08 #7
On Oct 16, 10:57 am, "Marco Nef" <maill...@shima .chwrote:
I'm looking for a template class that converts the
template argument to a string, so something like the
following should work:
Convert<float>: :Get() == "float";
Convert<3>::Get () == "3";
Convert<HelloWo rld>::Get() == "HelloWorld ";
The reason I need this is that in our design every class
of a certain hierarchy has a class name that must be
unique. So far I could not find a solution for template
classes.
What do you need those names for? Why do you want for it to
work with values as well as with types?
If typeid(X).name( ) is not sufficient for you (not portable,
may be not human readable), you'll have to provide a string
for every class yourself.
Thanks for your replies. I know about typeid and it is not
sufficient as "typeid->name" by the standard is not persistent
and not even unique.
What do you mean by "persistent " in this case?

And in practice, if the types are restricted to those you can
actually use to instantiate a template, about the only case
where they might not be unique in practice is if the types are
defined in anonymous namespace.
Another solution would be the following:
template<typena me Typestruct Convert
{
const String &GetName(VOI D) const { return Type::GetName() ; }
};
template<struct Convert<float>
{
const String &GetName(VOI D) const { return "float"; }
};

template<struct Convert<int>
{
const String &GetName(VOI D) const { return "int"; }
};
and so on...
So any classes provided as template argument need to implement
GetName(), for the base types there are specializations . This
works, but I don't really like it.
Which is understandable. (Although you could use a macro to
generate the specializations .)
I would love a struct like:
template<typena me Typestruct Convert
{
const String &GetName(VOI D) const { return XXXXXX; }
};
where XXXXXX is the question of this task :-)
The only thing anywhere like this in the standard is
typeid<Type>.na me().

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Oct 16 '08 #8
Thanks for your replies. I know about typeid and it is not
sufficient as "typeid->name" by the standard is not persistent
and not even unique.

What do you mean by "persistent " in this case?
My source for that is the book "Modern C++ Design" by Andrei Alexandrescu,
p. 206: "The way type_info::name is defined makes it unsuitable for anything
other than debuggin purposes. There is no guarantee that the string is the
actual class name, and worse, there is no guarantee that the string is
unique throughout the application."
....
"There is no guarantee that typeid(Line).na me() points to the same string
when the application is run twice."

Oct 16 '08 #9
On Oct 16, 2:41 pm, "Marco Nef" <maill...@shima .chwrote:
Thanks for your replies. I know about typeid and it is not
sufficient as "typeid->name" by the standard is not
persistent and not even unique.
What do you mean by "persistent " in this case?
My source for that is the book "Modern C++ Design" by Andrei
Alexandrescu, p. 206: "The way type_info::name is defined
makes it unsuitable for anything other than debuggin purposes.
There is no guarantee that the string is the actual class
name, and worse, there is no guarantee that the string is
unique throughout the application."
...
"There is no guarantee that typeid(Line).na me() points to the
same string when the application is run twice."
Aha. You mean that you can't use it as a type identifier in
persistent data.

The standard says that the string is implementation defined, and
in fact, an implementation which always returned "" would be
conforming. On the other hand, there are expectations due to
quality of implementation, which no compiler would dare neglect;
at the very least, you can certainly count on the string being
the same every time the function is called for the same type,
even in different runs, at least for non-local types (as long as
you haven't recompiled with a different compiler---or a
different version of the same compiler), and on the string being
different for classes with different basic names. In practice,
as long as the class isn't local or in an anonymous namespace, I
think you're OK.

Which, admittedly isn't very much, and I generally wouldn't use
it as a type identifier in external data (transmission protocols
or persistent data).

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Oct 17 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
11370
by: vpadial | last post by:
Hello, I want to build a library to help exporting c++ functions to a scripting languagge. The scripting language provides a function to register functions like: ANY f0() ANY f1(ANY) ANY f2(ANY, ANY) ANY f3(ANY, ANY, ANY)
1
4516
by: Adam Dziendziel | last post by:
Hi all! I'm writing a luabind/boost::python-like binding utility for a Squirrel language to generating wrapper-functions for C++ classes and have a problem with passing the pointer-to-member argument and deducing the type of them. I want to make a library which I can use like that: class_<fs::path, sq_filesystem::ttag>(v, "path", no_base)
3
1940
by: BigMan | last post by:
Here is a piece of code: #include <memory> using namespace std; template< typename SomeType > void f(auto_ptr_ref< SomeType >) { }
2
1344
by: gao_bolin | last post by:
I have the following situation: class A { public: virtual ~A() {} }; template < typename T > class B : public A
14
2912
by: Bart Samwel | last post by:
Hi everybody, I would really like some help explaining this apparent discrepancy, because I really don't get it. Here is the snippet: void foo(int&); void foo(int const&); template<typename T>
4
2523
by: George | last post by:
Dear All, I'm compiling the code below with IBM's xlC 6.0 and get the message, "rmspace.cpp", line 34.48: 1540-0298 (S) Template argument deduction cannot be performed using the function "template bool space_pred(basic_string<T,char_traits<T>,allocator<T> >::value_type)". If I use gcc4.0..2, I get,
4
7379
by: Damien | last post by:
Hi all, I've run into something confusing on MS VC6. Yeah I know it's old but that's what the client wants, so... I'm trying to pass a pointer to a member function as a template argument, and the compiler gives me an invalid template argument on the member function address if the member function returns a type. A member function with a void return type is fine. The example below demonstrates the problem:
1
3983
by: autumn | last post by:
Hi everybody, I'm having problem passing pointer to member object as template argument, seems VC 2005 does not allow 'pointer to base member' to 'pointer to derived member' conversion in template arguments, is this VC specific or a standard c++ behavior? the code looks like this: class Base { public: int member; };
4
3143
by: Jim Langston | last post by:
This should illistrate what I am trying to do: template <class T> T SomeFunction( T parm ) { return parm; } template <class T> class SomeClass
0
9698
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10916
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10598
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10657
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10299
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9436
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7836
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7022
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5684
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.