• Advertisement
Sign in to follow this  

Template specialization.

This topic is 4841 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Example:
template <typename X> struct Foo
 {
  template <typename Y> void bar(Y)
   {} 
 };
Your mission, should you choose to accept it, is to explain to me how to write a specialized version of Foo<X>::bar that takes an int.

Share this post


Link to post
Share on other sites
Advertisement
wouldn't it just be

template <typename X> struct Foo
{
template <typename Y> void bar(Y)
{}
template <int Y> void bar(Y)
{}
};


Cheers
Chris

Share this post


Link to post
Share on other sites
Do you need to specialise it instead of just overloading between a template and int?
template <typename X> struct Foo
{
template <typename Y> void bar(Y)
{
}
void bar(int);
};

template <typename X>
void Foo<X>::bar(int)
{
}



Enigma

Share this post


Link to post
Share on other sites
Basically its not possiable so your only solutions is to overload that member function for ints e.g.


template <typename X>
struct Foo {
template <typename Y> void bar(Y) {}
void bar(int) {}
};


int the version will always be invoked when an int is used,

however you can specialize a member function of specialized class template e.g.


#include <iostream>

template <typename X>
struct Foo {
template <typename Y> void bar(Y);
};

template <>
template <>
void Foo<double>::bar(int) { std::cout << "hi\n"; }

int main() {

Foo<double> b;

b.bar(10);

}

Share this post


Link to post
Share on other sites
Overloading the function seems to work fine. Why didn't I think of that?

Many thankyous and ++ratings to all. Well, except snk_kid, I already rated you up as much as I could.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement