【发布时间】:2014-05-05 12:13:56
【问题描述】:
我有一个函数,在一个库中,它是一个可变参数模板,并被其他程序使用。
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;
}
现在代码没问题,我的 lib 在 .so/dll 中编译得很好。
但是当我使用 f(...) 时,编译器只能找到“A.tpl”中的 f2,而不是 .so/dll(来自 .cpp)中的 f2。因此代码无效(再次),因为 ret 声明为 void。
所以,如果有人有任何想法来处理这个......
编辑
解决方案:
做3个解决方案,并添加A.tpl
template<>
void A::f2<void>();
【问题讨论】:
-
首先,应该说
void A::f<void,Args ...>(int id,Args&& ... args)而不是Ret A::f<void,Args ...>(int id,Args&& ... args) -
是的,对不起,这是一个错误(复制/过去)。
标签: c++ templates c++11 specialization variadic