我想在我的项目中为数据处理类创建一个模板接口.
我可以这样写:
template <class T>
class DataHandler
{
public:
void Process(const& T) = 0;
};
Run Code Online (Sandbox Code Playgroud)
然后,假设我以这种方式定义一个类:
class MyClass: public DataHandler<int>
{
void Process(const int&) { /* Bla-bla */ }
}
Run Code Online (Sandbox Code Playgroud)
现在,来问题,我可以以某种方式定义我的模板接口,作为参数,它不仅会收到类型T,而且会收到Process()函数的整个签名.
我想用这种方式工作:
class MyClass: public DataHandler<void (int&)>
{
void Process(const int&) { /* Bla-bla */ }
}
Run Code Online (Sandbox Code Playgroud)
可能吗?我知道,例如,boost :: signal以这种方式接收模板参数,但是,如果我理解正确的话,他们会在那里使用大量的黑魔法.
Joh*_*itb 12
是的,你可以.但是在C++ 03中,你必须为每个参数数量复制/粘贴代码(不是太糟糕,因为在这里你不需要const/non-const等的重载.这些constnes已经知道!).
template<typename FnType>
struct parm;
template<typename R, typename P1>
struct parm<R(P1)> {
typedef R ret_type;
typedef P1 parm1_type;
};
template <class T>
class DataHandler
{
typedef typename parm<T>::ret_type ret_type;
typedef typename parm<T>::parm1_type parm1_type;
public:
virtual ret_type Process(parm1_type t) = 0;
};
class MyClass: public DataHandler<void (const int&)>
{
void Process(const int&) { /* Bla-bla */ }
};
Run Code Online (Sandbox Code Playgroud)
在C++ 0x中,您将能够编写
template <class T>
class DataHandler;
template<typename R, typename ... P>
class DataHandler<R(P...)>
{
public:
virtual R Process(P... t) = 0;
};
class MyClass: public DataHandler<void (const int&)>
{
void Process(const int&) { /* Bla-bla */ }
};
Run Code Online (Sandbox Code Playgroud)
多好多了!
| 归档时间: |
|
| 查看次数: |
2054 次 |
| 最近记录: |