Gri*_*ner 2 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
{
}
Run Code Online (Sandbox Code Playgroud)
显然,我想出了一个'黑客'来解决我的问题,但为什么黑客需要?我们应该这样做吗?我所在的代码库有几十个实例,其中模板类具有某些成员函数的一些特殊化 - 而不是整个类.一位同事坚持认为这是不允许的.
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) { /* ... */ }
Run Code Online (Sandbox Code Playgroud)