5

I'm trying to implement a generic input stream of objects. That is, an interface or a lightweight proxy to an implementation. Details of implementation are unknown, i.e. a user of my library can write its own stream of, say, protobuf messages, pass it to my library and get back, say, stream of strings or any other stream. I'd like to keep the interface of stream generic so that users can write their own transformations and build transformation pipelines.

The interface of a stream should look like this:

template <typename T>
class Stream {
public:
    T* input();
}

On each call, input() shall return a next object in the stream or a null pointer, if the stream is empty.

The problem is that I'd like Stream<T> to be convertible to Stream<U> if T* is convertible to U*.

My unsuccessful attempt was to use pointer to implementation like this:

class StreamImplBase {
public:
    virtual void* input_raw() = 0;
}

template <typename T>
class StreamImpl: public StreamImplBase {
public:
    void* input_raw() final { return input(); }
    virtual T* input() = 0;
}

template <typename T>
class Stream {
    StreamImplBase* impl;
public:
    Stream(StreamImpl<T>* impl): impl(impl) {}
    T* input() { return static_cast<T*>(impl->input_raw()); }
}

The constructor from StreamImpl<T> guarantees that the void* returned from input_raw() was acquired by casting T to void*, therefore static_cast<T*> is safe.

However, if I perform any conversion, this statement will not be true. That is, building Stream<T> from StreamImpl<U> is unsafe even if U* is convertible to T*.

So my question is, how do I handle this problem?

I see the next possibilities:

  • store a converter (e.g. std::function<T*(void*)>) in the stream and update it on every cast. This seems unnecessarily expensive;

  • store the result of static_cast<U*>((T*)0) and add this result to the pointer obtained from input_raw(). This seems unnecessarily dangerous;

  • add the second template parameter OrigT and store StreamImpl<OrigT>* instead of storing StreamImplBase*. This will limit possible applications of the class, which I'd like to avoid;

  • using dynamic_cast is not an option because one can't dynamic_cast from void*.

Are there any other possibilities? How do others implement something like this?


Here's a usecase. Suppose we have a protobuf message X. I'd like this to work:

Stream<X> stream = ...;
Stream<google::protobuf::Message> raw_stream = stream;

Again, I don't know how Stream<X> is implemented. All I know is that it contains a shared pointer to some implementation which generates messages.

23
  • @Justin I've updated my question.
    – Zelta
    Commented Apr 28, 2018 at 0:03
  • 1
    You can't use a Stream<T>* pointer or Stream<T>& reference where a Stream<U>*/Stream<U>& is expected. What you want to do only makes sense if a Stream<U> object is constructed from a Stream<T> object. In which case, you would simply give Stream<U> an extra set of constructors/assignment-operators to handle T/Stream<T> as input. But I don't think that is what you are looking for. It would help if you would provide a minimal reproducible example showing how you want to use Stream, but I suspect the answer is going to be "it won't work that way". Commented Apr 28, 2018 at 0:22
  • @RemyLebeau I've updated my question with an example. In this example I suppose that Stream uses pimpl so that I can convert streams without converting heavy implementation.
    – Zelta
    Commented Apr 28, 2018 at 0:43
  • I've just realized that there is a pretty straight forward solution: create a stream implementation which would do the conversion and chain it to the original implementation. I'd say that I would like to avoid chaining implementations because it may be slow, but you may oppose that I already have two virtual calls and adding two more isn't a big deal.
    – Zelta
    Commented Apr 28, 2018 at 0:45
  • @Zelta w-- yeah, you have just written what I have just been writing about. You are not able to perform downcasts with generic types, which means that the only way of it working is making user able to cast the stream of hypothetical X to a stream of any hypothetical Y, which is not a thing that generics can do, i.e. generic type derivation. So the only solution that would work is a, again, generic, transformer object that pipes a stream of one type to be interpretable as a stream of some other type. Commented Apr 28, 2018 at 0:49

2 Answers 2

2

This:

template <typename T>
class Stream {
public:
  T* input();
};

is an object with one operation, which takes 0 arguments and returns a T*.

So is this:

std::function<T*()>

admittedly you invoke it like stream() instead of stream.input().

With this second solution, if U is a base of T, then you can convert the above to std::function<U*()>. Which solves your problem.

Personally I don't think typing .input between the name of your stream and () is worth a lot of work.

Type erasure that someone else has already done is best type erasure.

2
  • Yes you right! Replacing Stream with std::function is arguable, however, I've looked into the libc++ (llvm) implementation of std::function and it does exactly what's @IsaacCarolWeisberg suggested, i.e. it creates an std::function which holds a reference to std::function which holds the original function... which makes me think there's no way to do that without intermediate calls. So each conversion would add at least one virtual call, interesting!
    – Zelta
    Commented Apr 28, 2018 at 2:25
  • @Zelta Unless you have very deep hierarchies, I'm guessing it's not going to make much of a difference. Typical inheritance depths in my projects were 2 or 3 at max.
    – Justin
    Commented Apr 28, 2018 at 2:55
1

There is one C++ feature that allows conversion from a derived class to a base class when the two classes are not known in the same function: exceptions. Naturally, this is an ugly, ugly abuse, but it works:

#include <type_traits>
#include <stdexcept>

class StreamImplBase {
public:
    virtual void toss_input() = 0;
};

template <typename T>
class StreamImpl : public StreamImplBase {
public:
    virtual T* input() = 0;
    void toss_input() override
    { throw input(); }
};

template <typename T>
class Stream {
    StreamImplBase* impl;
public:
    template <typename U,
        std::enable_if_t<std::is_convertible<U*, T*>::value>* = nullptr>
    explicit Stream(StreamImpl<U>* impl) : impl(impl) {}

    template <typename U,
        std::enable_if_t<std::is_convertible<U*, T*>::value>* = nullptr>
    Stream(const Stream<U>& str) : impl(str.impl) {}

    T* input() const
    {
        try {
            impl->toss_input();
        } catch (T* ptr) {
            return ptr;
        }
        throw std::logic_error("Stream logic is broken?");
    }
};

See a complete example use on coliru. This could be improved by using std::shared_ptr<StreamImpl<U>> and std::shared_ptr<StreamImplBase>.

1
  • @Zelta Probably. I haven't done any measuring, but I wouldn't be surprised if the methods that chain calls to individual conversions are faster even when several types are chained.
    – aschepler
    Commented Apr 29, 2018 at 13:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.