gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:29:53 29 4
gpt4 key购买 nike

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

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 方法。

我的类.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 ,但是通过尝试使建议适应我的代码,我无法解决该错误。我希望,我的帖子是有效的。

最佳答案

编译器无法推断模板参数——它不知道你是否想调用 CFoo<float>::doSomething<float>(int) , CFoo<float>::doSomething<unsigned int>(int) , 管他呢。因此,您必须明确告诉它模板参数是什么:

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

关于c++ - 显式实例化的模板方法中的编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5251496/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com