使用 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。
最佳答案
它应该是int * const &
。您有 T = int *
,因此 const T = T const = int * const
。
请记住,U const &
表示“对常量 U
的引用”,而不是“对 ”——后者没有意义,因为 C++ 中的引用变量总是常量,即不能重新定位。在您的情况下,U
的常量引用U
是一个指向 int 的指针,而不是一个指向 const-int 的指针,这是两种不同的类型。
您当然也可以为 int const *
添加单独的特化:
template <> void Boogy<int const *>::Fn2(int const * const & in) { /* ... */ }
关于c++ - 使用 ptr-ref 类型的模板特化和特化规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10795187/