Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write a C or C++ library with "template"

Tags:

c++

c

templates

(1). When using C++ template, is it correct that the compiler (e.g. g++) will not compile the template definition (which can only be in header file not source file) directly, but generate the code based on template definition for each of its instantiations and then compile the generated code for its instantiations?

(2). If I want to write a C++ library which provide template classes and template functions, is it impossible to compile the library into shared file (.so, .a) because their instantiations will not be anywhere in the code of the library but only appear in the user's program? If yes, does it mean that template libraries are just source code files not precompiled files?

How is C++ standard template library (STL) implemented? Is its source code precompiled or compiled together with user's program?

(3). In C,

how to write a library that provide functions acting like template functions in C++? Is overloading a good solution?

If I have to write a procedure into a different function for different types of arguments, is there a good way for code reusing? Is this a good way to do it http://www.vlfeat.org/api/imop_8c_source.html? Any other ways?

Thanks and regards!

like image 589
Tim Avatar asked Feb 27 '10 20:02

Tim


1 Answers

When using C++ template, is it correct that the compiler (e.g. g++) will not compile the template definition.

Yes. It's a correct assumption.

A template definition is incomplete code. You need to fill in the template parameters before compiling it.

If I want to write a C++ library which provide template classes and template functions, is it impossible to compile the library into shared file (.so, .a)

No it's not possible. You can only compile individual instantiations of a template.

How is C++ standard template library (STL) implemented? Is its source code precompiled or compiled together with user's program?

A large part of the STL code resides in header files and gets compiled together with your application.

In C, how to write a library that provide functions acting like template functions in C++? Is this a good way to do it http://www.vlfeat.org/api/imop_8c_source.html? Any other ways?

Including the same file multiple times after redefining a macro (as demonstrated in the link you provided) is a good way to do this.

like image 86
Alex Jasmin Avatar answered Sep 30 '22 06:09

Alex Jasmin