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?
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'
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With