2012-05-29 42 views
2

使用2010 MSVC,我得到了以下行为:模板专业化与PTR-ref类型和特殊规则

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。

回答

5

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

记住U const &意思是“参照恒定U”,而不是“恒定参考U” —后者没有意义,因为在C基准变量++是总是恒定的,即,不能重新插拔。在你的情况U是一个指针到整型,而不是一个指针给const-INT,这是两种不同的类型。

你当然也可以添加一个单独的专门为int const *

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

尼斯... ...微妙 –

+0

当然!当你“从右向左读”时,它突然变得有意义。 Kerrek SB,你是那个让Luke的X-Wing退出沼泽的小绿人吗? ;-)至于对模板类的某些成员进行专门化的问题 - 没关系,对吧? –

+1

@LuchianGrigore:这就是我为什么要去做广告对* *前面加上'const'的英语和往常一样,系统地,把'const' * *后的类型其资格。只有内部类可以胜任* *前,它太容易搞砸了:( –