Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial C++ template specialization in dependent project

Suppose I have a library and multiple projects dependent on that library. The library headers already has some partial class specializations. I want to allow each dependent project to override with its own partial specializations. I need to achieve this all statically for performance reasons. Some simplified code is below.

Library code:

template <class A, class B, class Enable=void>
struct Widget;

struct Foo
{
};

template <class B>
struct Widget<Foo, B>
{
};

User code:

template <class B>
struct DoSpecialize;

template <class B>
struct Widget<Foo, B, enable_if< DoSpecialize<B> >::type
{
};

The problem here is we end up with multiple definitions of the same specialization. I think we need a disable_if<> somewhere. How could we avoid this?

like image 430
paperjam Avatar asked Dec 15 '25 15:12

paperjam


1 Answers

I'd suggest to solve it with separating the layers. The library has it's own specializations and the user can overwrite them if needed. If this is acceptable, the following is the library code:

namespace impl
{
    template <class A, class B, class Enable=void>
    struct Widget;
}

template <class A, class B, class Enable=void>
struct Widget : impl::Widget< A, B > {};

struct Foo
{
};

namespace impl
{
    template <class B>
    struct Widget<Foo, B>
    {
    };
}

and the user code stays as it is.

like image 110
Daniel Frey Avatar answered Dec 17 '25 22:12

Daniel Frey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!