简体   繁体   English

依赖项目中的部分C ++模板专业化

[英]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. 我想我们需要一个disable_if<> How could we avoid this? 我们怎么能避免这种情况?

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. 并且用户代码保持原样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM