具有模板功能的模板类 [英] Template class with template function

查看:29
本文介绍了具有模板功能的模板类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我这段代码有什么问题?

Can anyone tell what is wrong with this piece of code?

template<class X>
class C {
public:
    template<class Y> void f(Y); // line 4
};

template<class X, class Y>
void C<X>::f(Y y) { // line 8
    // Something.
}

int main() {
    C<int> c;
    char a = 'a';
    c.f(a);
    return 0;
}

编译:

$ g++ source.cpp 
source.cpp:8: error: prototype for ‘void C<X>::f(Y)’ does not match any in class ‘C<X>’
source.cpp:4: error: candidate is: template<class X> template<class Y> void C::f(Y)

我现在可以通过在第 4 行声明和定义函数来完成任务,但是与单独声明和定义函数相比,同时声明和定义函数会产生什么后果?(这不是关于在头文件与源文件中声明函数的讨论)

I now that I can accomplish the task by declaring and defining the function at line 4, but what would be the consequences of declaring and defining the function at the same time compared to doing it separately? (This is not a discussion about declaring a function at header vs source file)

注意:我看过这个问题 但似乎我唯一感兴趣的部分是分开的 =(

Note: I have seen this question but is seems that the only part that interests me was left apart =(

推荐答案

编译器已经告诉你答案了.类C是一个带参数的模板,成员函数f是模板成员函数,同样的定义:

The compiler already tells you the answer. The class C is a template with one parameter, and the member function f is a template member function, and you have to define it in the same way:

template <class X>
template <class Y>
void C<X>::f(Y y)
{
    // Something.
}

如果您在声明站点定义函数,您将隐式声明它inline;这实际上是唯一的区别.当然,可能会有风格上的考虑,例如永远不要将函数定义放在类定义中.

If you define the function at the declaration site, you'll implicitly declare it inline; that's about the only difference practically. There may be stylistic considerations, of course, e.g. never to put function definitions inside class definitions.

正如您正确地观察到的那样,您仍然需要在头文件中提供定义,因为无论何时使用它都需要实例化模板,因此您需要访问所有定义.

As you rightly observe, you will still have to provide the definition in the header file, since you will need to instantiate the template whenever you use it, and thus you need access to all the definitions.

这篇关于具有模板功能的模板类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆