I know that std::string is not designed for inheritance, however, I wonder why this class definition doesn't compile:
using std::string;
class ExtendedString: public string
{
public:
using string::string;
ExtendedString left(size_type n) const {
return substr(0, n>size()?size():n);
}
};
I get this error:
../../src/capel-tool.cpp:21:17: error: could not convert ‘std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::substr(std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::size_type, std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::size_type) const [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>; std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::size_type = long unsigned int](0, ((n > ((const ExtendedString*)this)->ExtendedString::<anonymous>.std::__cxx11::basic_string<char>::size()) ? ((const ExtendedString*)this)->ExtendedString::<anonymous>.std::__cxx11::basic_string<char>::size() : n))’ from ‘std::__cxx11::basic_string<char>’ to ‘ExtendedString’
I expected that the left
function would use any default constructor from std::string.
Even if I add an explicit constructor like this:
using std::string;
class ExtendedString: public string
{
public:
using string::string;
ExtendedString left(size_type n) const {
return substr(0, n>size()?size():n);
}
explicit ExtendedString(const std::string &s);
};
I still get the same error.
Only when I add a normal constructor:
using std::string;
class ExtendedString: public string
{
public:
using string::string;
ExtendedString(const std::string &s);
ExtendedString left(size_type n) const {
return substr(0, n>size()?size():n);
}
};
The code compiles ok.
Now imagine I want to make the same with a class that is designed for inheritance. Can not I just create this kind of wrapper in a way that the classes can be used interchangeablily without the need to create constructors thad would be created and called instead of being only "syntax sugar"
EDIT 1:
This suggested question does explain why my code does not work, but it does not propose any alternatives, as the accepted question does.