Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在c+中使用模板中的方法+;_C++_Templates - Fatal编程技术网

C++ 在c+中使用模板中的方法+;

C++ 在c+中使用模板中的方法+;,c++,templates,C++,Templates,我试图获得模板的基本视图,但我非常困惑。我有3个类,每个类基于模板: #include <map> using namespace std; typedef void (*cb1)(int a, int b); typedef void (*cb2)(int a, int b, int c); template <class H> class CHandle{ H m_id; }; template <typename H> class Hnd

我试图获得模板的基本视图,但我非常困惑。我有3个类,每个类基于模板:

#include <map>

using namespace std;

typedef void (*cb1)(int a, int b);
typedef void (*cb2)(int a, int b, int c);

template <class H>
class CHandle{
    H m_id;
};

template <typename H>
class HndFactory {
public:
    CHandle<H>* createHandle() {
        return new CHandle<H>();
    }
};

template <typename H>
CHandle<H> *createHandle(){
    CHandle<H> *h = new CHandle<H>();
    h->m_id = 100;
    return h;
}

template <class S>
class CSubscriber{
    S m_proc;
};

template <class H, class S>
class CEvent{
    H m_handle;
    S m_subscriber;
    std::map<CHandle<H>, CSubscriber<S> > m_map;
public:
    void subscribe(CHandle<H> *h);
    void unsubscribe(CHandle<H> *h);
};
template <class H, class S>
void CEvent<H, S>::subscribe(CHandle<H> *h){

}
int main(void){
    HndFactory<int> f;
    CSubscriber<cb1> s;
    CHandle<int> *h = f.createHandle();
    CEvent<CHandle<int>, CSubscriber<cb1> > myevent;
    myevent.subscribe(h);
    return 0;
}
我该如何正确地调用此方法?我认为当我创建对象“
h
”时,它已经定义了类型

致意 J.

CEvent-myevent;
应该是

CEvent<int, cb1> myevent;
CEvent-myevent;

错误消息实际上会告诉您这里有什么问题,只需稍微深入了解一下它的细节:

候选项为:void CEvent::subscribe(CHandle*)[带H=CHandle

从这里我们可以看到候选方法被列出,模板类型和类型被推断为
H
。当您用所讨论的类型替换H时,您会得到一个候选:

void CEvent::subscribe(CHandle*)
,现在希望它与传入的
CHandle
不匹配


相反,我认为您希望使用
CEvent myevent;
作为事件对象。请注意,您可能希望对
CEvent
类中的各种句柄和订阅者类型使用typedef,因为这可能使将来的维护更容易。

您需要将类成员更改为

std::map<H, S> m_map;

void subscribe(H *h);
void unsubscribe(CHandle<H> *h); 
您必须进行以下两个更改之一

您当前的代码执行模板操作两次。 与

模板
C类事件{

CEvent-myevent;
你所拥有的是

H == CHandle<int> & S = CSubscribe<cb1>
H==CHandle&S=c订阅
所以

void订阅(钱德尔*h);
变成

void subscribe(<CHandle<CHandle<H> > * h);
void订阅(
CEvent<int, cb1> myevent;
template <class H, class S>
class CEvent{
CEvent<CHandle<int>, CSubscriber<cb1> > myevent;
H == CHandle<int> & S = CSubscribe<cb1>
void subscribe(CHandle<H> *h);
void subscribe(<CHandle<CHandle<H> > * h);