Reputation: 4602
I need to implement the following interface:
class xml_writer
{
public:
virtual void write(const void* data, size_t size) = 0;
};
void xml_document::save(xml_writer& writer, const char_t* indent = "\t", unsigned int flags = format_default, xml_encoding encoding = encoding_auto) const;
I figured I could use a lambda like so:
// call save on XML passing lambda in place of xml_writer
std::array<char, 4096> request;
xml->save([&](const void* data, const std::size_t size) { std::memcpy(request.begin(), data, size); });
But alas it fails to compile in clang3.1!
Is it possible to use lambdas like this, i.e. in place of pure virtual inferfaces? My focus is reducing boilerplate code, not so much virtual function overhead.
Upvotes: 5
Views: 3497
Reputation: 208406
The simple answer is no, you cannot use lambdas to implement interfaces. The only interface of a lambda is the required operator()
, and that is non-virtual. Lambdas do not inherit from any type nor can they be inherited from.
What you can do is provide the definition of the extending type close to the use and implement the capture manually:
std::array<char,4096> request;
struct ToArrayWriter : xml_writer {
ToArrayWriter(std::array<char,4096>& array) : array(array) {}
void write( const void* data, size_t size ) {
std::memcpy(&array[0],data,size);
}
std::array<char,4096>& array;
} writer(request);
xml->save( writer );
Upvotes: 4