【问题标题】:How can I partially specialize class template non-type parameters如何部分专门化类模板非类型参数
【发布时间】:2018-12-03 04:26:08
【问题描述】:

我的问题很基本。我试图给自己一个方便的类模板实例化,它在数学上做一些直观的事情。我希望能够通过将其实例化为Q<31> 来实例化一个名为Q<0,31> 的类。根据cppreference.com,这个should be possible

template<class T> 
class A<int, T*, 5> {}; // #3: partial specialization where T1 is int, I is 5,
                        //     and T2 is a pointer

但是当我尝试这个时:

template< unsigned integral, unsigned fractional >
class Q: public Signed<integral + fractional + 1u> {};

// There's a shorthand for Q notation where you don't specify the number of integer bits, and it's assumed to be 0
template< unsigned fractional > class  Q<0u, fractional>: public Signed<fractional + 1> {};

static_assert( std::is_same< Q<31>, Q<0,31> >::value, "Partial specialization should be equivalent to no integer component");

然后我收到一条错误消息,提示我没有传递足够多的模板参数

【问题讨论】:

  • 似乎有很多不必要的代码来迷惑读者。只要把你所拥有的和你想要的。 Q&lt;31&gt; 不能自然地解释为 Q&lt;0,31&gt;,因为默认参数从左侧开始。
  • 您似乎误解了链接。部分特化不会改变您指定模板参数的方式,它会在提供的参数与部分特化匹配时替换实例化类的定义。

标签: c++ templates partial-specialization class-template


【解决方案1】:

专业化不是重载。它们是模式匹配。

没有魔法值,没有办法像你想要的那样“重载”模板。

template< unsigned fractional >
class  Q<0u, fractional>

这只是模式匹配。

你的论点总是

template< unsigned integral, unsigned fractional >
class Q

当有人通过0u 获得integral 时,您的专长匹配。所以它匹配

Q<0u, fractional>

它确实匹配

Q<fractional>

现在,如前所述,您可以使用魔法值来做到这一点:

template< unsigned integral, unsigned fractional=-1 >
class Q
template< unsigned fractional >
class Q<fractional, -1>:Q<0u, fractional> {}

但如果有人手动传递-1,也会发生这种情况。

中,您将能够将用户定义的类型作为模板非类型模板参数,因此您可以执行以下操作:

template< unsigned A, optional<unsigned> B = {} >
class Q;

template< unsigned integral, unsigned fractional >
class Q< integral, optional<unsigned>(fractional) > // 2 arg case

template< unsigned fractional >
class Q< fractional, nullopt >:Q<0u, fractional> {}; // 1 arg case

但这还不在这里。

【讨论】:

    【解决方案2】:

    你无法按照你想要的方式实现它,因为正如已经说过的那样不是和重载,但它可以使用具有部分专业化的别名模板:

    template<int, int B>
    struct Q {};
    
    template<int B>
    using Q0 = Q<0,B>;
    

    在您的代码中

    static_assert( std::is_same< Q0<31>, Q<0,31> >::value, "Partial specialization should be equivalent to no integer component");
    

    编译不会出错

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-05
      相关资源
      最近更新 更多