How to Adapt Existing C++ Libraries to Constraints? [closed]

  abstraction, c++, c++-concepts, c++20

Situation

I am writing an abstract (not in the "abstract class" or "pure virtual functions" sense) function, class, library, whatsoever and need certain functionality of types. These types are provided by many libraries, though the implementation of the specific method might be named differently.

Question

How do I adapt the libraries to the interface I want without changing that code?

Can I give my constraints multiple acceptable names for one interface? And have it map these names implicitly?
Do I have to write wrappers that map to the right method names? And how to best create that wrapper for huge class-types?

Example

Lets say, I want to implement some mathematical algorithm using just a norm and I have Real defined. Now I want to allow perfect flexibility and adaption to any type that affords a norm, but for this example just see in Boost: template<class Container> auto l2_norm(Container const & c); and Eigen: v.lpNorm<2>(). The concept normable below defines the requirement to types that my code should work with.

template <typename T>
concept normable = requires(T t_obj)
{
    { t_obj.norm() } -> std::convertible_to<Real>;
};

Options

  • I know that I could use inheritance with wrappers for all external code, but this doesn’t seem right and leads to virtual dispatch.
  • Apart from that, I believe that type erasure ( see https://github.com/tzlaine/type_erasure ) would fit quite well, but apparently requires me to write code three times (or have it generated) and wrapper classes as well. Moreover, this leads to beautiful template-errors.
  • Recently I discovered C++20 constraints, that would allow to just "demand" certain methods. It seems definitely much more elegant. But how to conform it with fixed libraries? -> this question

Source: Windows Questions C++

LEAVE A COMMENT