Search code examples
c++stringstreamstdstringuser-defined-types

convert user-defined type to std::string in C++


If I have a user-defined type such as:

 typedef std::string GenderType;
 GenderType gender;

is it possible to set gender equal to a std::string variable?

 std::string temp;
 temp = gender;

Do I need to extract the std::string somehow from GenderType? Is it safer to do this using stringstream?


Solution

  • With typedef you define a type alias, i.e. the two types are identical. There is no way to distinguish between these two types. You can use one whereever you can use the other one.

    So

    GenderType gender;
    std::string temp;
    temp = gender;
    

    is the same as

    std::string gender, temp;
    temp = gender;
    

    With type aliases, you can't add any type safety.