在哪里定义C ++类的成员模板函数和函数实例化? [英] Where to define C++ class member template function and functors that instantiate it?

查看:268
本文介绍了在哪里定义C ++类的成员模板函数和函数实例化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类Foo,用于一个小的独立项目。它在Foo.h中有一个类定义,实现文件Foo.cpp中的类成员函数的实现。

I have a class Foo which is used in a small standalone project. It has a class definition in Foo.h with the implementation for the class' member functions in an implementation file Foo.cpp.

第一个问题 - 成员函数之一Foo类是一个模板方法Foo :: doSomething(),这个方法的实现应该与Foo.h中的函数的声明一起出现吗?

First question - one of the member functions of class Foo is a template method Foo::doSomething(), is it correct that the implementation of this method should appear with the declaration of the function in Foo.h ?

Foo :: doSomething()将被实例化的模板参数是两个Functor类型之一 - 类CalcA和CalcB。

The template parameter which Foo::doSomething() will be instantiated with is one of two Functor types - class CalcA and CalcB.

应该:


  • (A)将两个Functor类的定义和实现全部放在Foo.cpp中(其中它们实际上由其他Foo成员函数的实现使用)

  • (C)调用Foo :: doSomething)。

  • (B)在Foo.h中定义和实现两个Functor类。我应该像Foo.h和Foo.cpp一样将普通类中的两个Functor的定义和实现拆分开来。

推荐答案

一般规则:

如果foo :: doSomething()在foo.cpp如果它是public或protected,通常),它必须在标题中。

If foo::doSomething() is used outside foo.cpp (i.e. if it's public or protected, usually), it must go in the header.

如果没有,放入cpp文件是完全正确的,甚至一个好主意(因为它保持杂乱的头文件)。

If not, putting in in the cpp file is perfectly ok, and even a good idea (as it keeps the clutter away from the header file).

因此,如果函子只用在cpp文件中,那么就把模板函数放在那里。如果这种变化,以后可以随时重构。

So, if the functors are only used in the cpp file, by all means put the template function there too. One can always refactor things later if this changes.

这篇关于在哪里定义C ++类的成员模板函数和函数实例化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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