从非模板参数化方法返回模板类型 [英] returning template types from non-template parameterized methods
问题描述
要定义一个模板类,我考虑三个不同的文件。该声明位于 .h
文件中,方法注释位于 .cpp
文件中,并且包括显式实例化在 .inc
文件中(通过在.cpp末尾添加一行,例如: #includebar-impl.inc code>)。
现在,这里是我的问题。我有两个模板类,说: Foo< S>
和 Bar< T>
。
在 Bar< T>
类中,我有一个方法返回一个模板类型 FooType *
<$ c $> p $ p>
template< class T>
class Bar {
....
template< class FooType>
FooType * doSomething(int);
....
};
由于编译器不知道 FooType *
是,我试图在 bar-impl.inc
文件中显式实例化 doSomething
// bar-impl.inc
模板类Foo< float> * Bar< float> :: doSomething(int);
但是,它没有工作,我得到一个错误:匹配函数调用
'Bar< float> :: doSomething(int&)'
make:*** [main]错误1
有人知道是否可以这样做?
作为功能模板。您需要在使用时显式实例化它们,除非模板参数可以从调用中派生。
因此,您不需要进行专门化, do在使用时指定 FooType
:
Bar< float&阿尔瓦尔某些情况, Foo< float> >(somevalue);
如果您总是想要返回
Foo< T> *
然后只需使用 Foo< T> * doSomething(int);
To define a templated class, I consider three different files. The declaration is in a .h
file, the methods implentations are in a .cpp
file, and explicit instantiations are included in a .inc
file (by adding a line at the end of the .cpp, e.g: #include "bar-impl.inc"
).
Now, here's my problem. I've two template classes, say: Foo<S>
and Bar<T>
.
Inside of the Bar<T>
class, I've a method that returns a template Type FooType*
( which with my explicit instantiation I would like it to be, for example, Foo<float>*
)
template<class T>
class Bar{
....
template <class FooType>
FooType* doSomething(int);
....
};
Since the compiler does not know what FooType*
is, I tried to explicitly instantiated the doSomething
method in the bar-impl.inc
file.
//bar-impl.inc
template class Foo<float> * Bar<float>::doSomething(int);
However, it didn't work and I get an error of: no matching function for call to
‘Bar<float>::doSomething(int&)’
make: *** [main] Error 1
Does anybody knows if it's possible to do that?
Methods templates work exactly the same way as function templates. You need to explicitly instantiate them upon use unless the template parameters can be derived from the call.
So you don't really need to make a specialization, what you need to do is specify the FooType
upon use:
Bar<float> somevar; somevar.doSomething< Foo<float> >(somevalue);
If you always want to return Foo<T>*
then just use Foo<T>* doSomething(int);
这篇关于从非模板参数化方法返回模板类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!