I've two different template classes. One of them has a member function that returns a pointer to an object of the other template class. Currently, I'm not able to compile the code below and any suggestions are really welcome.
main.cpp
#include <stdio.h>
#include <stdlib.h>
#include <foo.h>
#include <bar.h>
int main(int argc, char **argv){
...
int nParam;
...
CFoo<float> * pFoo = NULL;
pFoo = new CFoo<float>();
CBar<float> * pBar = NULL;
pBar = pFoo->doSomething(nParam); // error: no matching function for call to ‘CFoo<float>::doSomething(int)’
...
delete pFoo;
delete pBar;
return (0);
}
foo.h
#include <bar.h>
template < class FOO_TYPE >
class CFoo{
public:
...
template < class BAR_TYPE >
CBar<BAR_TYPE> * doSomething(int);
...
};
foo.cpp
template < class FOO_TYPE >
template < class BAR_TYPE >
CBar<BAR_TYPE> * CFoo<FOO_TYPE>::doSomething(int nParam){
...
}
#include "foo-impl.inc"
foo-impl.inc
template class CFoo<float>;
template class CFoo<double>;
template CBar<float>* CFoo<float>::doSomething( int );
template CBar<double>* CFoo<float>::doSomething( int );
template CBar<double>* 开发者_如何学JAVACFoo<double>::doSomething( int );
template CBar<float>* CFoo<double>::doSomething( int );
/*
I also tried the explicit instantiation in the last line, but I get the error below:
template-id ‘doSomething<CBar<float>*>’ for ‘CBar<float>* CFoo<float>::doSomething(int)’ does not match any template declaration
*/
// template CBar<float>* CFoo<float>::doSomething < CBar<float> * > ( int );
Consider that I need to call the doSomething
method inside of a member function
of a third class.
myclass.cpp
template < class FOO_TYPE, class BAR_TYPE >
void CMyClass<FOO_TYPE, class BAR_TYPE>::doSomeWork(CFoo<FOO_TYPE> * pFoo){
...
int nParam;
...
CBar<BAR_TYPE> * pBar = NULL;
pBar = pFoo->doSomething<BAR_TYPE>(nParam); //error: expected primary-expression before ‘>’ token
delete pBar;
...
}
Note that, I had a similar problem that I posted a while ago in this forum, but by trying to adapt the suggestion to my code, I couldn't solve the bug. I hope, my post is valid.
The compiler can't deduce the template arguments -- it doesn't know whether you want to call CFoo<float>::doSomething<float>(int)
, CFoo<float>::doSomething<unsigned int>(int)
, or whatever. So, you have to explicitly tell it what the template arguments are:
// Explicitly call the function with BAR_TYPE=float
pBar = pFoo->doSomething<float>(1);
精彩评论