Skip to main content
gamedev.net
🔒 Locked

[OOP] Double Interface

Started by ToohrVyk Jun 20, 2007 at 2:56 PM 2 replies 750+ views
Original Post
ToohrVyk
ToohrVyk
My GPGPU library currently contains two tied interfaces: Device, and Shader. The Shader does not know anything about Devices, but a Device may create (returned by a member function) and execute (as argument to a member function) Shaders. The Shader and Device are then implemented for different situations, such as CUDA_Kernel : public Shader and CUDA_Device : public Device. Obviously, a CUDA_Kernel contains CUDA-specific data (such as a CUmodule reference) which are not part of Shader and yet are required by CUDA_Device for execution. My problem (and it's a classic one) is about letting CUDA_Device access CUDA-specific members of CUDA_Kernel, when it receives a Shader through its overridden Device base class functions (and throw an exception if the Shader isn't the expected CUDA_Kernel). I should mention that my language does not support multiple dispatch in any way which would respect the open-closed principle. What solutions do you propose? Is there any elegant solution I might have overlooked, or is casting Shader to CUDA_Kernel the only possible one?
SamLowry
SamLowry
So, if I understand correctly, you want covariant argument types?

Afaik, it's not possible to do this in an "elegant" (which I assume means compile-time type-safe) way, as using interface-like concepts consists of deliberately splitting up static and dynamic type, meaning the argument type can only be known at runtime, hence the compiler is unable to check argument types. By this logic, templates/generics won't help either.

So, giving up compile-time type-safety, the only inelegance that remains is having to cast an argument once at the beginning of each method. I think all other solutions would be far more elaborate/inefficient than a little cast.

Keep in mind that I don't know which language you use, I assumed the C/C++/java/C#/... family.
ToohrVyk
ToohrVyk
An elegant solution would have been a generic visitor pattern, but sadly methods which are both virtual and generic (such as virtual template functions) are rarely supported.

Although in the end, I guess casting still is pretty clear.
vtchill
vtchill
I wish there was a good solution for this situation in c++. I generally implement a templated To, From checked_cast function and move on since I haven't found a better solution.

All the checked_cast does is attempt a dynamic_cast if in debug mode and throw an assert if it fails which basically helps for testing purposes. Then in release mode just a static_cast is done to avoid the dynamic_cast overhead.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.