I want to make a function associated to a data type say int that can be accessed using the dot operator such that:
int x = 9;
std::string s = x.ToString();
I know how to do so with std::string and the likes but not the int data type. Is that possible?
CodePudding user response:
No, this is not possible. An int
is a primitive type whereas a std::string
is a class type that contains methods.
However, you could create your own struct/class in order to implement this functionality. The struct Int
type has a constructor which takes in an integer and uses an initializer list :a(value)
(introduced in C 11) to assign the internal integer with a given value.
#include <string>
struct Int
{
int a;
Int(int value)
: a(value)
{}
std::string ToString() const { return std::to_string(a) };
};
Int a = 20;
std::string s = a.ToString();