Creating custom functions for strings in C ++

I've been using C ++ for about a month now, and I was wondering if it is possible to create custom user functions for something like a string. For example, to find the size of the string that you do stringname.size() But what if I wanted to create a function like stringname.customfunction() , I decided to decide what customfunction() does. I want to do this in order to create a .toLower () function that converts an entire string to the bottom. Sorry if this is a strange question, but any help would be greatly appreciated.

+5
source share
4 answers

You cannot directly, but you must emulate this, inheriting from std::string (or basic_string<char> ):

 class mystring : public std::string { public: void customfunction() { /* ... */ } }; 

Note. However, this is a bad idea. In addition to the link, which is @Cheers and hth. - Alf mentions that Herb Sutter discusses the overly broad std :: string interface and extends it even further - this is a bad idea.

+2
source

Yes, you can create custom functions, but not directly as member functions of an existing class.

The simplest and therefore best approach is to simply create autonomous functions.

This means that you name it as customfunction( s ) .

+4
source

You can achieve this by creating your own class of strings, but as I understand it, you mean calling something like "THE String".toLower() , for example, in python. As far as I know, this is actually impossible.

Once again, your best chance is to make your own class so you can call it MyString("THE String").toLower() . Or just create a toLower function that takes a string and returns a toLower("THE String") string toLower("THE String")

+3
source

It may be a little advanced and highly despised, but you can change the actual source files. I highly recommend you DO NOT do this.

You should just create a simple function void toLower(std::string str); which will convert it for you. (You would call this function with toLower(str); )

+1
source

Source: https://habr.com/ru/post/1235862/


All Articles