0

I want to create string class with some static templated information and identical std::string interface. I am lazy to wrap std::string so I am trying to use public inheritance and constructor inheritance:

#include <string>
using std::string;

template <typename Type = uint16_t>
class MyString : public string {
public:
   using string::string;
   using str_len_size = Type;
};

This code compiles without problem and I cant construct MyString from const char*:

MyString<uint16_t> str{"hello"};//OK

But when I try to construct MyString from std::string or assign std::string to it I have a compile errors:

std::string std_str{"hello"};
MyString<uint16_t> str{std_str};// error: no matching function for call ...

std::string std_str{"hello"};
MyString<uint16_t> str;
str = std_str;// error:  no known conversion for argument 1 from ‘std::string {aka std::basic_string<char>}’ to ‘lottery::base::MyString<short unsigned int>&&’

Why cant I constructor and assign MyString from std::string and how can I achieve this?

I use compiler gcc 7.3.1.

Pustovalov Dmitry
  • 998
  • 1
  • 9
  • 25
  • 2
    While it's not strictly a rule, a popular opinion is that [Thou shalt not inherit from std::vector](https://stackoverflow.com/questions/4353203/thou-shalt-not-inherit-from-stdvector) (or other standard containers). – François Andrieux Nov 02 '18 at 17:54
  • What "static templated information" are you trying to add, and are you sure it [doesn't already exist](https://en.cppreference.com/w/cpp/string/basic_string)? – TypeIA Nov 02 '18 at 17:56
  • 2
    @FrançoisAndrieux - Thou shall not do it if thou deletes your objects polymorphically. Rehashing that advice beyond that is bordering on cargo cult programming. – StoryTeller - Unslander Monica Nov 02 '18 at 17:57
  • It's a custom templated information, I want to deserealize a string and prepend before string buffer it's size but size variable should be variable length (1, 2, 4 bytes). – Pustovalov Dmitry Nov 02 '18 at 17:59
  • In short - your inherited constructor will not work with the object of base type. See comment in the duplicate for standarteeze. `MyString str(std_str.c_str());` works. – SergeyA Nov 02 '18 at 18:07
  • And there's this q&a about assignment https://stackoverflow.com/q/12009865/817643 – StoryTeller - Unslander Monica Nov 02 '18 at 18:08
  • Unrelated: You may find that the basis for `std::string`, [`std::basic_string` covers similar ground.](https://en.cppreference.com/w/cpp/string/basic_string) `std::string` is a `typedef` of `basic_string` . If this is for educational purposes, cool beans. Learning is good. If not, you may be reinventing the wheel. – user4581301 Nov 02 '18 at 18:35

0 Answers0