[英]template specialization for static member functions; howto?
我正在尝试使用模板特化来实现带有句柄的模板函数。
以下代码在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();
}
}
我已经尝试将它移出类(该类没有模板化)并进入命名空间,但后来我得到错误“显式专门化不能有一个存储类”。 我已经阅读了很多关于此的讨论,但人们似乎并不同意如何专门化功能模板。 有任何想法吗?
当您专门化模板化方法时,必须在类括号之外执行此操作:
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'关键字。 类之外的静态关键字具有与您可能想要的不同的特定含义。
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'
}
这不是你的问题的直接答案,但你可以写这个
template <typename T>
static T safeGuiCall(boost::function<T ()> _f)
{
if (_f.empty())
throw GuiException("Function pointer empty");
{
ThreadGuard g;
return _f();
}
}
它应该工作,即使_f()返回'void'
编辑:在更一般的情况下,我认为我们应该更喜欢函数重载而不是特化。 以下是一个很好的解释: http : //www.gotw.ca/publications/mill17.htm
您可以像在类之外定义成员函数一样声明显式特化:
class A
{
public:
template <typename T>
static void foo () {}
};
template <>
void A::foo<void> ()
{
}
您的问题似乎与boost :: function - 以下专业化工作:
template <typename T>
T safeGuiCall()
{
return T();
}
template <>
void safeGuiCall<void>()
{
}
int main() {
int x = safeGuiCall<int>(); // ok
//int z = safeGuiCall<void>(); // this should & does fail
safeGuiCall<void>(); // ok
}
我遇到了类似的问题。 如果你看一下原来的帖子,我就把第一个静态输入了,但是拿出了第二个,并且BOTH错误就消失了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.