2

How could I convert any type to a string in C++?

std::string val;

template<typename T> std::string AnyToString(T val) {
     return (std::string)val;
}

template<typename T> void SetVal(T val) {
    this->val = AnyToString(val);
}

int main() {
    SetVal(10);
    return 0;
}

Above code gives me an error, cannot convert int to string. reinterpret_cast<>, static_cast<>, etc. don't work either.

Kara
  • 6,115
  • 16
  • 50
  • 57
Teytix
  • 85
  • 1
  • 4
  • 10

3 Answers3

4

First off, some style issue: (std::string)val is a C-style cast, something that is frowned upon in the C++ community. There are several disadvantages, including lack of type safety and that you cannot find it in a large amount of C++ code. C++ introduces different types of casts for different goals: static_cast<>,dynamic_cast<>, reinterpret_cast<> and const_cast<>.

However, you shouldn't try to just "cast" an int to a string, that doesn't work. Please use std::to_string: http://en.cppreference.com/w/cpp/string/basic_string/to_string

Klaas van Gend
  • 1,105
  • 8
  • 22
1

You can convert the "any" type to a string by testing for all existing types (e.g. int, string, float, etc.) using the typeid() function.

  • value.type() : will return the type of the value.
  • typeid(float) : will return the id of a float type value.

To put all this together, we can create a function that tests all the types possible and then convert the value to a string depending on its type.

Here is the complete solution :

#include<any>
        
std::any variable;
std::string anyToString = anyToString(variable);
    
string anyToString(any value) {
    
        //add whatever types you would like as an if condition
        if(value.type() == typeid(string))
            return std::any_cast<string> (value);
    
        if (value.type() == typeid(float))
            return to_string(std::any_cast<float> (value));
    
        if (value.type() == typeid(int))
            return to_string(std::any_cast<int> (value));
}
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 11 '23 at 13:30
0

C++11 introduces std::stoi (and variants for each numeric type) and std::to_string, the counterparts of the C atoi and itoa but expressed in term of std::string.

#include <string>

int val = 5967;
std::string s = std::to_string(val); // std::string("5967")

Same question is addressed at: Easiest way to convert int to string in C++

Community
  • 1
  • 1
dipendra009
  • 299
  • 2
  • 7