I'm developing a "MemRef" class to use in place of std::string
, to cut down on const
string copying by passing around pointers instead. A MemRef object consists simply of a char*
ptr and an int
len.
I want to make it possible to call the function foo(const string&)
as foo(my_memref)
, by defining a method to convert a MemRef into a std::string
. What I've read about "conversion constructors" seems to only address the issue of converting from some other data type to my class, rather than the other way around. I've also read that conversion constructors are often more trouble than they're worth.
Is there a way to define an implicit "convert to some other type" method in a class, such that I can write (e.g.) display_string(my_memref)
?
UPDATE: Here's the current attempt:
// This is a "cast operator", used when assigning a MemRef to a string
MemRef::operator std::string() const {
// construct a string given pointer and length
std::string converted(ptr_, len_);
return converted;
}
And here's the use:
:
const string foo("ChapMimiReidAnn");
MemRef c(foo.c_str(), 4);
begin_block(c);
:
void
begin_block(const string& s) {
cout << "begin_block('" << s << "')" << endl;
}
But here's the error:
c++ -c -pg -O0 -fno-strict-aliasing --std=c++11 -arch x86_64 -I/Users/chap/private/WDI/git -I/Users/chap/private/WDI/git/include -I/usr/local/mysql/include -I/usr/local/include memref_test.cpp
c++ -c -pg -O0 -fno-strict-aliasing --std=c++11 -arch x86_64 -I/Users/chap/private/WDI/git -I/Users/chap/private/WDI/git/include -I/usr/local/mysql/include -I/usr/local/include MemRef.cpp
c++ -o memref_test memref_test.o MemRef.o -L/usr/local/mysql/lib -lmysqlclient -pg
Undefined symbols for architecture x86_64:
"MemRef::operator std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >() const", referenced from:
_main in memref_test.o