Is it possible to make a string as a template parameter? - c++

Is it possible to make a string as a template parameter and how? Like
A<"Okay"> is a type.
Any string (std::string or c-string) is fine.

Yes, but you need to put it in a variable with external linkage
(or does C++11 remove the requirement for external linkage).
Basically, given:
template <char const* str>
class A { /* ... */ };
this:
extern char const okay[] = "Okay";
A<okay> ...
works. Note thought that it is not the contents of the string
which define uniqueness, but the object itself:
extern char const okay1[] = "Okay";
extern char const okay2[] = "Okay";
Given this, A<okay1> and A<okay2> have different types.

Here's one way to make the string contents determine uniqueness
#include <windows.h> //for Sleep()
#include <iostream>
#include <string>
using namespace std;
template<char... str>
struct TemplateString{
static const int n = sizeof...(str);
string get() const {
char cstr[n+1] = {str...}; //doesn't automatically null terminate, hence n+1 instead of just n
cstr[n] = '\0'; //and our little null terminate
return string(cstr);
}
};
int main(){
TemplateString<'O','k','a','y'> okay;
TemplateString<'N','o','t',' ','o','k','a','y'> notokay;
cout << okay.get() << " vs " << notokay.get() << endl;
cout << "Same class: " << (typeid(okay)==typeid(notokay)) << endl;
Sleep(3000); //Windows & Visual Studio, sry
}

Related

Pointers to undefined functions and parameters in C ++

I have the following code:
#include<iostream>
using namespace std;
void saludo();
void despedida();
int main(){
void (*Ptr_Funciones[2])() = {saludo, despedida};
(Ptr_Funciones[0])();
(Ptr_Funciones[1])();
return 0;
}
void saludo(){
cout<<"\nHola mundo";
}
void despedida(){
cout<<"\nAdios mundo"<<endl<<endl;
}
Based on this, a few questions were generated which I investigated before asking but did not fully understand.
The questions are:
How do I make an array of functions, if they are of a different type?
I know that in C ++ this notation is used for undetermined parameters: (type var ...) The
thing is, I don't know how to interact with them inside the function.
If questions 1 and 2 are possible, can these points be combined when creating function
arrays?
I really have investigated. But I can't find much information, and the little I did find I didn't understand very well. I hope you can collaborate with me.
Thank you very much.
How do I make an array of functions, if they are of a different type?
You can, but you don't want to. It doesn't make semantic sense. An array is a collection of the same kind of thing. If you find that you need to make a collection of different kinds of things, there are several data structures at your disposal.
I know that in C++ this notation is used for undetermined parameters: (type var ...) The thing is, I don't know how to interact with them inside the function.
Here's how you can use the syntax you mention. They're called variadic functions.
If questions 1 and 2 are possible, can these points be combined when creating function arrays?
Erm, I can't imagine why/when a combination of these two would be needed, but out of intellectual curiosity, awayyy we go...
A modified version of the code from the reference link above that kinda does what you want (i've used a map instead of an array, cuz why not):
#include <iostream>
#include <cstdarg>
#include <unordered_map>
template<typename T>
using fooptr = void (*) (T *t...);
struct A {
const char *fmt;
A(const char *s) :fmt{s} {}
};
struct B : public A {
B(const char *s) : A{s} {}
};
void simple_printf(A *a...)
{
va_list args;
auto fmt = a->fmt;
va_start(args, a);
while (*fmt != '\0') {
if (*fmt == 'd') {
int i = va_arg(args, int);
std::cout << i << '\n';
} else if (*fmt == 'c') {
// note automatic conversion to integral type
int c = va_arg(args, int);
std::cout << static_cast<char>(c) << '\n';
} else if (*fmt == 'f') {
double d = va_arg(args, double);
std::cout << d << '\n';
}
++fmt;
}
va_end(args);
}
int main()
{
A a{"dcff"};
B b{"dcfff"};
std::unordered_map<size_t, fooptr<struct A>> index;
index[1] = simple_printf;
index[5] = simple_printf;
index[1](&a, 3, 'a', 1.999, 42.5);
index[5](&b, 4, 'b', 2.999, 52.5, 100.5);
}
This still really doesn't do what you wanted (i.e., give us the ability to choose from different functions during runtime). Bonus points if you understand why that's the case and/or how to fix it to do what you want.
Use a type alias to make things readable:
Live On Coliru
using Signature = void();
Signature* Ptr_Funciones[] = { saludo, despedida };
Prints
Hola mundo
Adios mundo
More flexible:
You can also use a vector:
Live On Coliru
#include <iostream>
#include <vector>
using namespace std;
void saludo() { cout << "\nHola mundo"; }
void despedida() { cout << "\nAdios mundo" << endl << endl; }
int main() {
vector Ptr_Funciones = { saludo, despedida };
Ptr_Funciones.front()();
Ptr_Funciones.back()();
}
Prints the same.
More Flexibility: Calleables of Different Types
To bind different types of functions, type-erasure should be used. std::function helps:
Live On Coliru
#include <iostream>
#include <functional>
#include <vector>
using namespace std;
void saludo(int value) { cout << "\nHola mundo (" << value << ")"; }
std::string despedida() { cout << "\nAdios mundo" << endl << endl; return "done"; }
int main() {
vector<function<void()>>
Ptr_Funciones {
bind(saludo, 42),
despedida
};
Ptr_Funciones.front()();
Ptr_Funciones.back()();
}
Prints
Hola mundo (42)
Adios mundo
Here is one solution that is possible, whether it fits your needs I'm not sure.
#include <Windows.h>
#include <iostream>
void saludo()
{
std::cout << "\nHola mundo" << std::endl;;
}
void despedida()
{
std::cout << "\nAdios mundo" << std::endl;
}
void* fnPtrs[2];
typedef void* (VoidFunc)();
int main()
{
fnPtrs[0] = saludo;
fnPtrs[1] = despedida;
((VoidFunc*)fnPtrs[0])();
((VoidFunc*)fnPtrs[1])();
std::getchar();
return 0;
}

How to access a constexpr string that is defined in a struct?

How to properly access the string "bye" from the struct?
#include <iostream>
static constexpr char hi[] = "hi";
struct S{ static constexpr char bye[] = "bye"; };
int main(int argc, char *argv[]) {
typedef struct S ST;
std::cout << hi << std::endl; // this prints "hi"
std::cout << sizeof(ST::bye) << std::endl; // this correctly prints 4
std::cout << ST::bye << std::endl; // this does not compile with "undefined reference"
}
I'm working with a c++ framework that has some configuration in this format (in multiply nested structs even) to make its values available during compile time. I'm not deep enough into C++ to grasp the underlying issue here. Also I cannot argue about why this approach on implementing the configuration was chosen and cannot change it.
This can be made working by redefining the static constexpr outside the struct:
#include <iostream>
static constexpr char hi[] = "hi";
struct S{ static constexpr char bye[] = "bye"; };
constexpr char S::bye[]; // <<< this line was missing
int main(int argc, char *argv[]) {
typedef struct S ST;
std::cout << hi << std::endl; // this prints "hi"
std::cout << sizeof(ST::bye) << std::endl; // this correctly prints 4
std::cout << ST::bye << std::endl; // Now this prints "bye"
}
Or by compiling using c++17 which makes this obsolete.
Related links:
constexpr static member before/after C++17
What does it mean to "ODR-use" something?

why is it possible to use 'string' as the name of a variable

I'm a beginner in C++ and I'm doing one of the exercises in Stroustrup's Programming Principles And Practice Using C++.
This exercise wants me to experiment with legal and illegal names.
void illegal_names()
{
// the compiler complains about these which made sense:
// int double =0;
// int if =0;
// int void = 0;
// int int = 0;
// int while =0;
// string int = "hello";
//
// however, this is legal and it runs without a problem:
double string = 0.0;
cout << string<< endl;
}
My question is, what makes string different than any other types? Are there other types that is special like string?
All of those other names are reserved words in the C++ language. But "string" is not. Even though string is a commonly used data type, it is built out of more basic types and defined in a library which itself is written in C++.
string is not a keyword so it may be used as an identifier. All other statemenets in the code segment are erroneous because there are used keywords as identifiers.
As for standard class std::string then you can even write in a block scope
std::string string;
In this case the identifier string declared in the block scope will hides type std::string
For example
#include <iostream>
#include <string>
int main()
{
std::string string = "Hello, string";
std::cout << string << std::endl;
return 0;
}
in C++ std::string is a defined data type (class), not a keyword. it's not forbidden to use it as variable name. it is not a reserved word. consider a C++ program, which also works:
#include <iostream>
class xxx {
int x;
public:
xxx(int x_) : x(x_) {}
int getx() { return x;}
};
int main()
{
xxx c(4);
std::cout << c.getx() << "\n";
int xxx = 4; // this works
std::cout << xxx << "\n";
return 0;
}
this the same case as with string. xxx is user defined data type and as you can see it is not reserved.
the image below shows list of reserved keywords in c++.

Is there a C++ way to write file with any type of data?

Like this function in C:
size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream );
I've looked in C++ file stream and found this one:
ostream& write ( const char* s , streamsize n );
this one only accepts char* instead of void*
but does it really matter if I use a C-style fwrite function in c++?
Streams are probably what you're looking for unless I misunderstand your question. There are many flavors that handle different jobs, like outputting to a file:
#include <cstdlib>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream f("c:\\out.txt");
const char foo[] = "foo";
string bar = "bar";
int answer = 42;
f << foo << bar<< answer;
return 0;
}
...building strings like you would with printf:
#include <cstdlib>
#include <sstream>
#include <string>
#include <iostream>
using namespace std;
int main()
{
stringstream ss;
const char foo[] = "foo";
string bar = "bar";
int answer = 42;
ss << foo << bar<< answer;
string my_out = ss.str();
return 0;
}
...and they can even handle your own types, if you tell them how:
#include <cstdlib>
#include <string>
#include <iostream>
using namespace std;
class MyGizmo
{
public:
string bar_;
int answer_;
MyGizmo() : bar_("my_bar"), answer_(43) {};
};
ostream& operator<<(ostream& os, const MyGizmo& g)
{
os << g.bar_ << " = " << g.answer_;
return os;
}
int main()
{
MyGizmo gizmo;
cout << gizmo;
return 0;
}
You can use either one. Using char * instead of void * doesn't make much real difference -- both fwrite and ostream::write are typically used for a variety of data types (with with C++, you need to add an explicit cast to char *, where in C the cast will happen implicitly, assuming you've included a proper prototype for fwrite).
In C++ you will want to use std::ofstream objects to write to a file. They can accept any type of data using the << operator, in much the same way that std::cout works for writing to the console. Of course, just like std::cout, if you want to print a custom type, you will need to define an operator<< overload for it.
An example:
std::ofstream outfile("myfile.txt");
int i = 5;
double d = 3.1415926535898;
std::string s = "Hello, World!";
outfile << i << std::endl;
outfile << d << std::endl;
outfile << s << std::endl;
To use std::ofstream, you need to #include <fstream>.
The outfile object will automatically close the file when it destructs, or you can call its close() method.
Contrary to already given answers, there is an important difference between fwrite() and ostream::write().
fwrite() writes binary data unmodified (well, on those poor non-Unix platforms there is endline translation, unless the file is opened in binary mode).
ostream::write() uses locale to transform every character, this is why it accepts char* rather than void*. Normally, it uses the default "C" locale, which does not do any transformation.
Just keep in mind that basic_ostream is a formatter on top of basic_streambuf, not a binary sink.

Unmangling the result of std::type_info::name

I'm currently working on some logging code that supposed to - among other things - print information about the calling function. This should be relatively easy, standard C++ has a type_info class. This contains the name of the typeid'd class/function/etc. but it's mangled. It's not very useful. I.e. typeid(std::vector<int>).name() returns St6vectorIiSaIiEE.
Is there a way to produce something useful from this? Like std::vector<int> for the above example. If it only works for non-template classes, that's fine too.
The solution should work for gcc, but it would be better if I could port it. It's for logging so it's not so important that it can't be turned off, but it should be helpful for debugging.
Given the attention this question / answer receives, and the valuable feedback from GManNickG, I have cleaned up the code a little bit. Two versions are given: one with C++11 features and another one with only C++98 features.
In file type.hpp
#ifndef TYPE_HPP
#define TYPE_HPP
#include <string>
#include <typeinfo>
std::string demangle(const char* name);
template <class T>
std::string type(const T& t) {
return demangle(typeid(t).name());
}
#endif
In file type.cpp (requires C++11)
#include "type.hpp"
#ifdef __GNUG__
#include <cstdlib>
#include <memory>
#include <cxxabi.h>
std::string demangle(const char* name) {
int status = -4; // some arbitrary value to eliminate the compiler warning
// enable c++11 by passing the flag -std=c++11 to g++
std::unique_ptr<char, void(*)(void*)> res {
abi::__cxa_demangle(name, NULL, NULL, &status),
std::free
};
return (status==0) ? res.get() : name ;
}
#else
// does nothing if not g++
std::string demangle(const char* name) {
return name;
}
#endif
Usage:
#include <iostream>
#include "type.hpp"
struct Base { virtual ~Base() {} };
struct Derived : public Base { };
int main() {
Base* ptr_base = new Derived(); // Please use smart pointers in YOUR code!
std::cout << "Type of ptr_base: " << type(ptr_base) << std::endl;
std::cout << "Type of pointee: " << type(*ptr_base) << std::endl;
delete ptr_base;
}
It prints:
Type of ptr_base: Base*
Type of pointee: Derived
Tested with g++ 4.7.2, g++ 4.9.0 20140302 (experimental), clang++ 3.4 (trunk 184647), clang 3.5 (trunk 202594) on Linux 64 bit and g++ 4.7.2 (Mingw32, Win32 XP SP2).
If you cannot use C++11 features, here is how it can be done in C++98, the file type.cpp is now:
#include "type.hpp"
#ifdef __GNUG__
#include <cstdlib>
#include <memory>
#include <cxxabi.h>
struct handle {
char* p;
handle(char* ptr) : p(ptr) { }
~handle() { std::free(p); }
};
std::string demangle(const char* name) {
int status = -4; // some arbitrary value to eliminate the compiler warning
handle result( abi::__cxa_demangle(name, NULL, NULL, &status) );
return (status==0) ? result.p : name ;
}
#else
// does nothing if not g++
std::string demangle(const char* name) {
return name;
}
#endif
(Update from Sep 8, 2013)
The accepted answer (as of Sep 7, 2013), when the call to abi::__cxa_demangle() is successful, returns a pointer to a local, stack allocated array... ouch!
Also note that if you provide a buffer, abi::__cxa_demangle() assumes it to be allocated on the heap. Allocating the buffer on the stack is a bug (from the gnu doc): "If output_buffer is not long enough, it is expanded using realloc." Calling realloc() on a pointer to the stack... ouch! (See also Igor Skochinsky's kind comment.)
You can easily verify both of these bugs: just reduce the buffer size in the accepted answer (as of Sep 7, 2013) from 1024 to something smaller, for example 16, and give it something with a name not longer than 15 (so realloc() is not called). Still, depending on your system and the compiler optimizations, the output will be: garbage / nothing / program crash.
To verify the second bug: set the buffer size to 1 and call it with something whose name is longer than 1 character. When you run it, the program almost assuredly crashes as it attempts to call realloc() with a pointer to the stack.
(The old answer from Dec 27, 2010)
Important changes made to KeithB's code: the buffer has to be either allocated by malloc or specified as NULL. Do NOT allocate it on the stack.
It's wise to check that status as well.
I failed to find HAVE_CXA_DEMANGLE. I check __GNUG__ although that does not guarantee that the code will even compile. Anyone has a better idea?
#include <cxxabi.h>
const string demangle(const char* name) {
int status = -4;
char* res = abi::__cxa_demangle(name, NULL, NULL, &status);
const char* const demangled_name = (status==0)?res:name;
string ret_val(demangled_name);
free(res);
return ret_val;
}
Boost core contains a demangler. Checkout core/demangle.hpp:
#include <boost/core/demangle.hpp>
#include <typeinfo>
#include <iostream>
template<class T> struct X
{
};
int main()
{
char const * name = typeid( X<int> ).name();
std::cout << name << std::endl; // prints 1XIiE
std::cout << boost::core::demangle( name ) << std::endl; // prints X<int>
}
It's basically just a wrapper for abi::__cxa_demangle, as has been suggested previously.
If all we want is the unmangled type name for the purpose of logging, we can actually do this without using std::type_info or even RTTI at all.
A slightly portable solution that works for the big 3 main compiler front-ends (gcc, clang, and msvc) would be to use a function template and extract the type name from the function name.
gcc and clang both offer __PRETTY_FUNCTION__ which is the name of a current function or function template with all type-argument in the string. Similarly MSVC has __FUNCSIG__ which is equivalent. Each of these are formatted a little differently, for example, for a call of void foo<int>, the compilers will output something different:
gcc is formatted void foo() [with T = int; ]
clang is formatted void foo() [T = int]
msvc is formatted void foo<int>()
Knowing this, it's just a matter of parsing out a prefix and suffix and wrapping this into a function in order to extract out the type name.
We can even use c++17's std::string_view and extended constexpr to get string names at compile-time, just by parsing the name of a template function. This could also be done in any earlier C++ version, but this will still require some form of string parsing.
For example:
#include <string_view>
template <typename T>
constexpr auto get_type_name() -> std::string_view
{
#if defined(__clang__)
constexpr auto prefix = std::string_view{"[T = "};
constexpr auto suffix = "]";
constexpr auto function = std::string_view{__PRETTY_FUNCTION__};
#elif defined(__GNUC__)
constexpr auto prefix = std::string_view{"with T = "};
constexpr auto suffix = "; ";
constexpr auto function = std::string_view{__PRETTY_FUNCTION__};
#elif defined(_MSC_VER)
constexpr auto prefix = std::string_view{"get_type_name<"};
constexpr auto suffix = ">(void)";
constexpr auto function = std::string_view{__FUNCSIG__};
#else
# error Unsupported compiler
#endif
const auto start = function.find(prefix) + prefix.size();
const auto end = function.find(suffix);
const auto size = end - start;
return function.substr(start, size);
}
With this, you can call get_type_name<T>() to get a std::string_view at compile-time indicating the unmangled type name.
For example:
std::cout << get_type_name<std::string>() << std::endl;
on GCC will output:
std::__cxx11::basic_string<char>
and on clang will output:
std::basic_string<char>
Live Example
A similar augmentation to this approach which avoids a prefix and suffix is to assume that the function name is the same for all types, and search for a sentinel type to parse out the offset to the sentinel from each end. This ensures that the string searching only happens once, and the offset is assumed to find the string name each time. For example, using double as a simple sentinel:
template <typename T>
constexpr auto full_function_name() -> std::string_view
{
#if defined(__clang__) || defined(__GNUC__)
return std::string_view{__PRETTY_FUNCTION__};
#elif defined(_MSC_VER)
return std::string_view{__FUNCSIG__};
#else
# error Unsupported compiler
#endif
}
// Outside of the template so its computed once
struct type_name_info {
static constexpr auto sentinel_function = full_function_name<double>();
static constexpr auto prefix_offset = sentinel_function.find("double");
static constexpr auto suffix_offset = sentinel_function.size() - prefix_offset - /* strlen("double") */ 6;
};
template <typename T>
constexpr auto get_type_name() -> std::string_view
{
constexpr auto function = full_function_name<T>();
const auto start = type_name_info::prefix_offset;
const auto end = function.size() - type_name_info::suffix_offset;
const auto size = end - start;
return function.substr(start, size);
}
Live Example
This isn't portable to all compilers, but can be modified for any compiler that offers a __FUNCSIG__/__PRETTY_FUNCTION__ equivalent; it just requires a bit of parsing.
note: This hasn't been fully tested, so there may be some bugs; but the primary idea is to parse any output that contains the name in totality -- which is often a side-effect of __func__-like outputs on compilers.
This is what we use. HAVE_CXA_DEMANGLE is only set if available (recent versions of GCC only).
#ifdef HAVE_CXA_DEMANGLE
const char* demangle(const char* name)
{
char buf[1024];
unsigned int size=1024;
int status;
char* res = abi::__cxa_demangle (name,
buf,
&size,
&status);
return res;
}
#else
const char* demangle(const char* name)
{
return name;
}
#endif
Here, take a look at type_strings.hpp it contains a function that does what you want.
If you just look for a demangling tool, which you e.g. could use to mangle stuff shown in a log file, take a look at c++filt, which comes with binutils. It can demangle C++ and Java symbol names.
It's implementation defined, so it's not something that's going to be portable. In MSVC++, name() is the undecorated name, and you have to look at raw_name() to get the decorated one.
Just a stab in the dark here, but under gcc, you might want to look at demangle.h
I also found a macro called __PRETTY_FUNCTION__, which does the trick. It gives a pretty function name (figures :)). This is what I needed.
I.e. it gives me the following:
virtual bool mutex::do_unlock()
But I don't think it works on other compilers.
The accepted solution [1] works mostly well.
I found at least one case (and I wouldn't call it a corner case) where it does not report what I expected... with references.
For those cases, I found another solution, posted at the bottom.
Problematic case (using type as defined in [1]):
int i = 1;
cout << "Type of " << "i" << " is " << type(i) << endl;
int & ri = i;
cout << "Type of " << "ri" << " is " << type(ri) << endl;
produces
Type of i is int
Type of ri is int
Solution (using type_name<decltype(obj)>(), see code below):
cout << "Type of " << "i" << " is " << type_name<decltype(i)>() << endl;
cout << "Type of " << "ri" << " is " << type_name<decltype(ri)>() << endl;
produces
Type of i is int
Type of ri is int&
as desired (at least by me)
Code
.
It has to be in an included header, not in a separately compiled source, due to specialization issues. See undefined reference to template function for instance.
#ifndef _MSC_VER
# include <cxxabi.h>
#endif
#include <memory>
#include <string>
#include <cstdlib>
template <class T>
std::string
type_name()
{
typedef typename std::remove_reference<T>::type TR;
std::unique_ptr<char, void(*)(void*)> own
(
#ifndef _MSC_VER
abi::__cxa_demangle(typeid(TR).name(), nullptr,
nullptr, nullptr),
#else
nullptr,
#endif
std::free
);
std::string r = own != nullptr ? own.get() : typeid(TR).name();
if (std::is_const<TR>::value)
r += " const";
if (std::is_volatile<TR>::value)
r += " volatile";
if (std::is_lvalue_reference<T>::value)
r += "&";
else if (std::is_rvalue_reference<T>::value)
r += "&&";
return r;
}
Not a complete solution, but you may want to look at what some of the standard (or widely supported) macro's define. It's common in logging code to see the use of the macros:
__FUNCTION__
__FILE__
__LINE__
e.g.:
log(__FILE__, __LINE__, __FUNCTION__, mymessage);
A slight variation on Ali's solution. If you want the code to still be very similar to
typeid(bla).name(),
writing this instead
Typeid(bla).name() (differing only in capital first letter)
then you may be interested in this:
In file type.hpp
#ifndef TYPE_HPP
#define TYPE_HPP
#include <string>
#include <typeinfo>
std::string demangle(const char* name);
/*
template <class T>
std::string type(const T& t) {
return demangle(typeid(t).name());
}
*/
class Typeid {
public:
template <class T>
Typeid(const T& t) : typ(typeid(t)) {}
std::string name() { return demangle(typ.name()); }
private:
const std::type_info& typ;
};
#endif
type.cpp stays same as in Ali's solution
Following Ali's solution, here is the C++11 templated alternative which worked best for my usage.
// type.h
#include <cstdlib>
#include <memory>
#include <cxxabi.h>
template <typename T>
std::string demangle() {
int status = -4;
std::unique_ptr<char, void (*)(void*)> res{
abi::__cxa_demangle(typeid(T).name(), NULL, NULL, &status), std::free};
return (status == 0) ? res.get() : typeid(T).name();
}
Usage:
// main.cpp
#include <iostream>
namespace test {
struct SomeStruct {};
}
int main()
{
std::cout << demangle<double>() << std::endl;
std::cout << demangle<const int&>() << std::endl;
std::cout << demangle<test::SomeStruct>() << std::endl;
return 0;
}
Will print:
double
int
test::SomeStruct
Take a look at __cxa_demangle which you can find at cxxabi.h.
// KeithB's solution is good, but has one serious flaw in that unless buf is static
// it'll get trashed from the stack before it is returned in res - and will point who-knows-where
// Here's that problem fixed, but the code is still non-re-entrant and not thread-safe.
// Anyone care to improve it?
#include <cxxabi.h>
// todo: javadoc this properly
const char* demangle(const char* name)
{
static char buf[1024];
size_t size = sizeof(buf);
int status;
// todo:
char* res = abi::__cxa_demangle (name,
buf,
&size,
&status);
buf[sizeof(buf) - 1] = 0; // I'd hope __cxa_demangle does this when the name is huge, but just in case.
return res;
}
I've always wanted to use type_info, but I'm sure that the result of the name() member function is non-standard and won't necessarily return anything that can be converted to a meaningful result.
If you are sticking to one compiler, there maybe a compiler specific function that will do what you want. Check the documentation.
boost::typeindex provides something helpful.
#include <boost/type_index.hpp>
#include <iostream>
#include <vector>
class Widget {};
int main() {
using boost::typeindex::type_id_with_cvr;
const std::vector<Widget> vw;
std::cout << type_id_with_cvr<decltype(vw)>().pretty_name() << std::endl;
std::cout << type_id_with_cvr<decltype(vw[0])>().pretty_name() << std::endl;
return 0;
}
The output is
std::vector<Widget, std::allocator<Widget> > const
Widget const&
What is worthy of notice is that type_id_with_cvr preserves reference and c/v qualifiers, while typeid doesn't. See the following example:
#include <iostream>
#include <boost/type_index.hpp>
#include <typeindex>
#include <vector>
#include <typeinfo>
class Widget {};
template <typename T>
void f(const T &param) {
std::cout << typeid(param).name() << std::endl;
std::cout
<< boost::typeindex::type_id_with_cvr<decltype(param)>().pretty_name()
<< std::endl;
}
int main() {
const std::vector<Widget> vw(1);
f(&vw[0]);
return 0;
}
The output is
PK6Widget
Widget const* const&
Here, typeid produces PK6Widget, which means Pointer to Konst Widget. The number '6' is the length of the name 'Widget'. This is not the correct type of param, in which the reference and const qualifier are dropped.
The type_id_with_cvr actually uses the demangling functions in boost::core, as has been mentioned in this answer. To preserve the cv qualifiers or reference, it just defines an empty template named cvr_saver and then passes cvr_saver<type> to typeid.
Effective Modern C++ Item 4 talks about this.