Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

template specialization for static member functions; howto?

I am trying to implement a template function with handles void differently using template specialization.

The following code gives me an "Explicit specialization in non-namespace scope" in gcc:

template <typename T>
static T safeGuiCall(boost::function<T ()> _f)
{
    if (_f.empty())
        throw GuiException("Function pointer empty");
    {
        ThreadGuard g;
        T ret = _f();
        return ret;
    }
}

// template specialization for functions wit no return value
template <>
static void safeGuiCall<void>(boost::function<void ()> _f)
{
    if (_f.empty())
        throw GuiException("Function pointer empty");
    {
        ThreadGuard g;
        _f();
    }
}

I have tried moving it out of the class (the class is not templated) and into the namespace but then I get the error "Explicit specialization cannot have a storage class". I have read many discussions about this, but people don't seem to agree how to specialize function templates. Any ideas?

like image 985
Rolle Avatar asked Apr 20 '09 09:04

Rolle


Video Answer


2 Answers

When you specialize a templated method, you must do so outside of the class brackets:

template <typename X> struct Test {}; // to simulate type dependency

struct X // class declaration: only generic
{
   template <typename T>
   static void f( Test<T> );
};

// template definition:
template <typename T>
void X::f( Test<T> ) {
   std::cout << "generic" << std::endl;
}
template <>
inline void X::f<void>( Test<void> ) {
   std::cout << "specific" << std::endl;
}

int main()
{
   Test<int> ti;
   Test<void> tv;
   X::f( ti ); // prints 'generic'
   X::f( tv ); // prints 'specific'
}

When you take it outside of the class, you must remove the 'static' keyword. Static keyword outside of the class has a specific meaning different from what you probably want.

template <typename X> struct Test {}; // to simulate type dependency

template <typename T>
void f( Test<T> ) {
   std::cout << "generic" << std::endl;
}
template <>
void f<void>( Test<void> ) {
   std::cout << "specific" << std::endl;
}

int main()
{
   Test<int> ti;
   Test<void> tv;
   f( ti ); // prints 'generic'
   f( tv ); // prints 'specific'
}
like image 159
David Rodríguez - dribeas Avatar answered Oct 08 '22 01:10

David Rodríguez - dribeas


It's not directly an answer to your question but you can write this

template <typename T>
static T safeGuiCall(boost::function<T ()> _f)
{
        if (_f.empty())
                throw GuiException("Function pointer empty");
        {
                ThreadGuard g;
                return _f();
        }
}

It should work even if _f() return 'void'

Edit : In a more general case, I think we should prefer function overloading instead of specialization. Here is a good explanation for this : http://www.gotw.ca/publications/mill17.htm

like image 29
Rexxar Avatar answered Oct 08 '22 02:10

Rexxar