开发者

Template functions and class use in different files

I want to have开发者_JAVA百科 a template function defined in one file and used in many files. Does this work the same way regular function prototypes work? So I can define it once and just include the prototype in other files? I have the same question for classes, must I include the full defintion of a template class in each header file, just as I would for a class? Would it cause and error if I defined a template function twice in separate files or would this just go unchecked.

One more question, what is the format for a template function prototype?


No, it's not the same as a regular function. With a regular function, you can declare

void foo(int);
void foo(double);

in a header, define the functions in some source file, such as foo.cc, #include the header in any source file that has to use those functions, such as bar.cc, and let the linker do the rest. The compiler will compile bar.cc and produce bar.o, confident that you've defined the functions somewhere, and if you haven't then you'll get a link-time error.

But if you're using a template:

template <typename T>
void foo(T) ...

try to imagine how that would work. The source files foo.cc and bar.cc are independent and know nothing about each other, except that they agree on what's in the headers they both #include (that's the whole idea). So bar.cc doesn't know how foo.cc implements things, and foo.cc doesn't know what bar.cc will do with these functions. In this scenario, foo.cc doesn't know what type bar.cc will specify for T. So how can foo.cc possible have definitions for every typename under the sun?

It can't, so this approach isn't allowed. You must have the whole template in the header, so that the compiler can gin up a definition for foo(int), or foo(string), or foo(myWeirdClass), or whatever bar.cc calls for, and build it into bar.o (or complain if the template makes no sense for that type).

The same goes for classes.

The rules are a little different for template specializations, but you should get a good grip on the basics before trying the advanced techniques.


See this FAQ. Especially, items 12, 13 and 14 deals with separating the declaration and definition of template functions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜