Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I specialize this template member function?

I have this setup:

class DontUse;

template<class T,class U = DontUse, class V = SomeStandardType>
class Foo
{
   public:
     void bar(U &uh);
};

When U is set to DontUse, I want bar to be an empty function. In all other cases, I want bar to have some implementation. I tried doing this using specialization, but this code (which I realize is somehow incorrect) doesn't compile:

template<class T,class V> void Foo<T,DontUse,V>::bar(DontUse &none){}
template<class T,class U,class V> void Foo<T,U,V>::bar(U &uh)
{
  //do something here
}

The error message is this (MSVC10):

1>path_to_project: error C2244: 'Foo<T,U,V>::bar' : unable to match function definition to an existing declaration

and it points to the line of the first template specialization.

How do I do this correctly?

Here's the actual code, although it's reduced to the minimalist part that's relevant:

    struct DontUse;

    template<typename Derived, typename Renderer =  DontUse, typename TimeType = long>
    class Gamestate
    {
    public:

        void Render(Renderer &r);

    };

    template<typename Derived, typename TimeType> void Gamestate<Derived, DontUse,TimeType>::Render( DontUse){}
    template<typename Derived, typename Renderer, typename TimeType> void Gamestate<Derived,Renderer,TimeType>::Render(Renderer &r)
    {
        static_cast<Derived*>(this)->Render(r);
    }
like image 249
TravisG Avatar asked Feb 25 '26 11:02

TravisG


1 Answers

You cannot specialize individual members of a template. You have to specialize the class itself:

class DontUse;

template<class T, class V>
class Foo<T, DontUse, V>
{
   public:
     void bar(DontUse)
     { }
};
like image 73
Bo Persson Avatar answered Feb 27 '26 02:02

Bo Persson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!