Created
July 1, 2017 07:12
-
-
Save rhulha/7a8912a5026a5a0b7fc8ab25eeccf62f to your computer and use it in GitHub Desktop.
Testing C++ Template Inheritance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define _WIN32_WINNT 0x0601 | |
#ifdef _MSC_VER | |
#include <boost/config/compiler/visualc.hpp> | |
#endif | |
#include <cstdlib> | |
#include <string> | |
#include <sstream> | |
#include <iostream> | |
#include <boost/asio.hpp> | |
#include <boost/iostreams/stream.hpp> | |
#include <boost/iostreams/concepts.hpp> | |
#include <boost/make_shared.hpp> | |
#include <boost/exception/all.hpp> | |
using namespace boost; | |
class socket_stream_source : public iostreams::source | |
{ | |
int max=100; | |
public: | |
socket_stream_source(int max) | |
{ | |
this->max = max; | |
} | |
std::streamsize read(char* s, std::streamsize n) | |
{ | |
printf("n: %lld\n", n); | |
if (!max) | |
return -1; | |
for (int i = 0; i < n; i++) { | |
if (!max--) | |
return i; | |
s[i] = 0; | |
} | |
return n; | |
}; | |
}; | |
int main_this_fails() | |
{ | |
// this fails completely because templated classes not be upcast even if the type parameters are inherited | |
boost::iostreams::stream<boost::iostreams::source> *sock_stream2 = | |
static_cast <boost::iostreams::stream<boost::iostreams::source>*>( | |
new boost::iostreams::stream<socket_stream_source>() | |
); | |
// try with reinterpret_cast, this fails because boost::iostreams::source does not contain a read function | |
boost::iostreams::stream<boost::iostreams::source> *sock_stream2 = | |
reinterpret_cast <boost::iostreams::stream<boost::iostreams::source>*>( | |
new boost::iostreams::stream<socket_stream_source>() | |
); | |
// try with c style cast, this fails because boost::iostreams::source does not contain a read function | |
boost::iostreams::stream<boost::iostreams::source> *sock_stream3 = | |
(boost::iostreams::stream<boost::iostreams::source>*) | |
new boost::iostreams::stream<socket_stream_source>(); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment