静态成员函数模板专用化;如何? [英] template specialization for static member functions; howto?
问题描述
我试图实现与手柄无效不同使用模板特殊化模板函数。
I am trying to implement a template function with handles void differently using template specialization.
下面的代码给我一个非命名空间范围明确的专业化的gcc:
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'
}
必须删除static关键字。 ,在课堂外static关键字拥有你可能想要什么不同的特定含义。
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屋!