多条件模板专业化C ++

时间:2019-05-06 02:15:13

标签: c++ templates template-specialization

我有一个结构

template <typename A, typename B>
struct foo {static const int type = 0;};

AB都是算术运算时,我希望实现有所不同。但是,这没有用。

template <typename A, typename B, typename std::enable_if<
        std::is_arithmetic<A>::value && 
        std::is_arithmetic<B>::value, bool>::type = 0>
struct foo<A, B> {static const int type = 1;}

我收到编译器错误default template arguments may not be used in partial specializations。那我该如何做呢?

要记住的一件事是,我还想拥有其他可能看起来像这样的更简单的模板专业化。

template <>
struct foo<string, vector<int>> {static const int type = 2;}

总而言之,我希望第一个定义像默认值一样,然后定义一堆专门的实现,其中一个是通用的实现。

1 个答案:

答案 0 :(得分:3)

您可以像{p>一样分别定义primary templatepartial specializationfull specialization

// the primary template
template <typename A, typename B, typename = void>
struct foo {static const int type = 0;};

// the partial specialization
template <typename A, typename B>
struct foo<A, B, typename std::enable_if<
        std::is_arithmetic<A>::value && 
        std::is_arithmetic<B>::value>::type> {static const int type = 1;};

// the full specialization
template <>
struct foo<string, vector<int>, void> {static const int type = 2;};

LIVE