使用ptr-ref类型和专业化规则的模板专业化

时间:2012-05-29 07:58:13

标签: c++ templates template-specialization

使用MSVC 2010,我得到以下行为:

template <class T> class Boogy
{
public:
    void Fn( T in )
    {
    }

    void Fn2( const T& in)
    {
    }
};

template <> void Boogy<int>::Fn( int in ) //builds ok
{
}

template <> void Boogy<int*>::Fn( int* in ) //builds ok
{
}

template <> void Boogy<int>::Fn2( const int& in ) //builds ok
{
}

template <> void Boogy<int*>::Fn2( const int*& in ) //DOES NOT BUILD
{
}

typedef int* intStar;
template <> void Boogy<intStar>::Fn2( const intStar& in ) //builds ok
{
}

显然,我想出了一个'黑客'来解决我的问题,但为什么黑客需要?我们应该这样做吗?我所在的代码库有几十个实例,其中模板类具有某些成员函数的一些特殊化 - 而不是整个类。一位同事坚持认为这是不允许的。

TIA。

1 个答案:

答案 0 :(得分:5)

应该是int * const &。您有T = int *,所以const T = T const = int * const

请记住,U const &表示“引用常量U”,而不是“常量引用U ” - 后者没有意义,因为C ++中的参考变量总是不变,即无法重新设定。在你的情况下,U是指向int的指针,而不是指向const-int的指针,它们是两种不同的类型。

您当然也可以为int const *添加单独的专精:

template <> void Boogy<int const *>::Fn2(int const * const & in) { /* ... */ }