Re: Function template specialization
sheffmail@mail.ru wrote:
On Jun 5, 1:05 am, Victor Bazarov <v.Abaza...@comAcast.net> wrote:
sheffm...@mail.ru wrote:
I have the following code:
template <class T>
struct MyS
{
};
template<class T>
inline const T& function(const std::locale& loc)
{
std::cout << "generic" << std::endl;
}
template <class CharType, class Traits, class Allocator>
inline const MyS< std::basic_string<CharType, Traits, Allocator> >&
function< MyS< std::basic_string<CharType, Traits, Allocator> >
> (const std::locale& loc)
{
std::cout << "specialized" << std::endl;
}
int main(int argc, char* argv[])
{
function< MyS<std::string> >(std::locale()); //Should print
"specialized"
function< MyS<std::wstring> >(std::locale()); //Should print
"specialized"
function< MyS<int> >(std::locale()); //Should print "generic"
return 0;
}
Which doesn't compile, I believe it's because you can't partially
specialize function templates.
Correct.
> But I really need to
get the desired behavior(Note the "Should print"s in comments), how
can this be done ?
You can invent your own traits class and specialise that (or *on* that).
Full specialisations of function templates *are* allowed.
Oh, forgot to mention that I need to get this behavior without
changing the signature of generic function:
template<class T>
inline const T& function(const std::locale& loc)
Is it possible ?
So, you have a function template that you want to behave differently if
you give it some special *set of* Ts, right. And that set is unbounded,
right? If it is, the solution is to wrap those in a class template and
specialise that:
template<class T> struct Caller {
static T& call(const std::locale& loc) {
return function<T>(loc);
}
};
template<class T, class U> struct Caller<MyS<T,U> > {
static MyS<T,U>& call(const std::locale& loc) {
return function<MyS<T,U> >(loc);
}
};
Of course in that case you need to refactor the code that calls the
functions from
function<blah>(loc);
to
Caller<blah>::function(loc);
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask