Why?
Sometimes we might want to know the type of a C++ object at compile time, for example, to use it in template metaprogramming or to enforce certain constraints. For instance we most of the time don't need big metaprogramming to know about a JSON container type.
So I wrote a container called 'as_string' with basic support for primitive types and stl containers too.
Compiler Explorer
Explore the code in Compiler Explorer.
Code Snippet
#include <stdint.h>
#include <iostream>
#include <string>
template <typename V>
struct as_string
{
static constexpr auto data = V::data;
};
template <>
struct as_string<std::size_t>
{
static constexpr auto data = "std::size_t";
};
template <>
struct as_string<bool>
{
static constexpr auto data = "bool";
};
template <>
struct as_string<std::string>
{
static constexpr auto data = "std::string";
};
template <>
struct as_string<int>
{
static constexpr auto data = "int";
};
struct json_container final
{
static constexpr auto data = "json_container";
};
int main() {
std::cout << as_string<json_container>::data << std::endl;
std::cout << as_string<std::size_t>::data << std::endl;
std::cout << as_string<int>::data << std::endl;
std::cout << as_string<bool>::data << std::endl;
std::string foo= "foo";
std::cout << as_string<decltype(foo)>::data << std::endl;
return 0;
}