显式实例化模板方法中的编译错误

时间:2011-03-09 20:04:44

标签: c++ templates instantiation

我有两个不同的模板类。其中一个具有成员函数,该函数返回指向另一个模板类的对象的指针。 目前,我无法编译下面的代码,我们非常欢迎任何建议。

的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>* CFoo<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 ); 

考虑一下我需要在第三类doSomething内调用member function方法。

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;
    ...
} 

请注意,我有a similar problem that I posted a while ago in this forum,但是通过尝试将建议调整到我的代码,我无法解决错误。我希望,我的帖子是有效的。

1 个答案:

答案 0 :(得分:5)

编译器无法推断出模板参数 - 它不知道您是否要调用CFoo<float>::doSomething<float>(int)CFoo<float>::doSomething<unsigned int>(int)或其他任何内容。因此,您必须明确告诉它模板参数是什么:

// Explicitly call the function with BAR_TYPE=float
pBar = pFoo->doSomething<float>(1);