问题描述:

Using MSVC 2010, I get the following behaviour:

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

{

}

Obviously, I've come up with a 'hack' to sort my issue out, but why is the hack necessary? And should we be doing this at all? The code base I'm in has dozens of instances where template classes have SOME specialisations of SOME of the member functions - not of the whole class. A colleague is adamant that this isn't allowed.

TIA.

网友答案:

It should be int * const &. You have T = int *, so const T = T const = int * const.

Remember that U const & means "reference to constant U", and not "constant reference to U" — the latter doesn't make sense, since reference variables in C++ are always constant, i.e. cannot be reseated. In your case the U is a pointer-to-int, and not a pointer-to-const-int, which are two different types.

You can of course also add a separate specialization for int const *:

template <> void Boogy<int const *>::Fn2(int const * const & in) { /* ... */ }
相关阅读:
Top