我在库中有一个函数,它是一个可变参数模板,并被其他程序使用。
1
A.hpp
class A {
template<typename Ret,typename ... Args>
static Ret f(int id,Args&& ... args);
};
#include "A.tpl"
A.tpl
template<typename Ret,typename ... Args>
Ret A::f(int id,Args&& ... args)
{
//do somthing with args and id
Ret ret;
/// do somthing with ret
return ret;
}
我的问题是: 如果 Ret 为空,则代码不正确。 所以我尝试构建 f 的特化:
2
A.tpl
template<typename ... Args>
void A::f<void,Args ...>(int id,Args&& ... args)
{
//do somthing with args and id
return;
}
template<typename Ret,typename ... Args>
Ret A::f(int id,Args&& ... args)
{
//do somthing with args and id
Ret ret;
/// do somthing with ret
return ret;
}
但是这个代码是不正确的。
所以我尝试拆分代码:
3
A.hpp
class A {
template<typename Ret,typename ... Args>
static Ret f(int id,Args&& ... args);
template<typname Ret>
static Ret f2();
}
#include "A.tpl"
A.tpl
template<typename Ret,typename ... Args>
Ret A::f(int id,Args&& ... args)
{
//do somthing with args and id
return f2<Ret>();
}
template<typename Ret>
Ret A::f2()
{
Ret ret;
/// do somthing with ret
return ret;
}
A.cpp
template<>
void A::f2<void>()
{
return;
}
现在代码没问题了,我的库在 .so/dll 中编译得很好。
但是当我使用 f(...) 时,编译器只能找到来自“A.tpl”的 f2,而不是 .so/dll(来自 .cpp)中的 f2。因此代码无效(再次),因为 ret 声明为 void。
所以,如果有人有任何想法来处理这个......
编辑
解决方法:
做第3题,加入A.tpl
template<>
void A::f2<void>();
最佳答案
你不能部分特化一个函数/方法...
您可以使用可以部分专门化的辅助类。
template<typename Ret, typename ... Args> struct helper;
template<typename ... Args>
struct helper<void, Args...>
{
void operator() (int id, Args&& ... args) const { /* Implementation for void */ }
};
template<typename Ret, typename ... Args>
struct helper<Ret, Args...>
{
Ret operator() (int id, Args&& ... args) const { /* Implementation for non void case */ }
};
class A {
template<typename Ret,typename ... Args>
static Ret f(int id, Args&& ... args)
{
return helper<Ret, Args...>()(id, std::forward<Args>(args)...);
}
};
关于c++ - 部分特化可变参数模板类型名为 void,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23472189/