c ++中断模板特化歧义

时间:2012-10-16 03:21:18

标签: c++ template-meta-programming partial-specialization

我一直在阅读 C ++模板元编程并进行其中包含的练习,并遇到了一个问题。这个小例子可以看出问题的核心:

    template <class A, class B>
    struct C;

    template <class A>
    struct C<A,A>
    {
      typedef some_type type;
    };

    template <class A, class B>
    struct C<A*,B>
    {
      typedef some_other_type type;
    };

    int main()
    {
      C<int*,int*> c;
    }

这无法编译,因为c的类型不明确。编译器不能告诉它要实例化哪个特化,但是,我知道在这种情况下我希望调用第一个特化。到目前为止我提出的解决方案是像这样重写它

    template <class A, class B>
    struct C;

    template <class A, class B>
    struct C<A*,B>
    {
      typedef typename boost::mpl::if_c<boost::is_same<A*,B>::value,
                                        some_type, some_other_type>::type type;
    };

这个解决方案的问题在于我实际上对每个指针,const,引用和数组类型都有部分特化,所以我必须将这个检查单独添加到每个特化。

我的问题是,是否有一些方法可以获得之前的精确紧凑特化,并以某种方式调整它以便编译器实例化特化

     template <class A>
     struct C<A,A>
     {
       typedef some_type type;
     };

而不是任何其他专业化的歧义?

对于那些感兴趣的人,我正在研究的问题是第2章问题1。

1 个答案:

答案 0 :(得分:2)

您可以向基本模板添加另一个参数,并使用它来启用/禁用您的专业化。例如,您可能有:

template< class A, class B, class Enable = void >
struct C;
template< class A >
struct C<A, A, void> {...};
template< class A, class B >
struct C<A*, B, typename boost::disable_if<boost::is_same<A*, B> >::type> {...};

现在,如果你想处理const指针或任何其他东西你可以根据类型特征(is_constis_pointer,...)扩展你的条件!

相关问题