Few days ago, I have met with using "c++ templates" into libraries problem.
Firstly, I inserted my template into lib.cpp file:
// lib.h:
template <class T>
void function(const T& t);
// lib.cpp:
#include <iostream>
template <class T>
void function(const T& t)
{
std::cout << sizeof(t) << std::endl;
}
// main.cpp:
int main()
{
function(5);
return 0;
}
In that case lib.a (lib.lib) don't include "function" function.And as result we get:
unresolved external symbol "void __cdecl function<int>(int const &)"If we can read B. Stroustrup, C++ Programming Language, chapter 13.7, we can find 'export' keyword. This keyword should solve such problem. But on current moment gcc says:
warning: keyword 'export' not implemented, and will be ignoredwhen you try to use it.
This is the reason, why on current moment we can't insert template into lib.cpp. Templates are not compiling into object files like special "template" type. Only instantiated function will be saved into library.
The only way is using appendix function, like:
lib.cpp
...
void a()
{
function(6);
}
I don't think that such solution can be really good one, because compiler can use our functionYou can find more information using: http://cpp.tribe.net/thread/5e706586-7594-4be5-9e69-bf20bbfc5c2f
Russian translate:
Несколько дней назад я столкнулся с проблемой создания шаблона внутри библиотеки. Сначала хотелось получить полностью внесенный в статическую библиотеку код шаблона. Т.е. разместить заголовок шаблона в *.h, а код определения в соответствующий *.cpp.
// lib.h:
template<class T>
void function(const T& t);
// lib.cpp:
#include <iostream>
template<class T>
void function(const T& t)
{
std::cout << sizeof(t) << std::endl;
}
// main.cpp:
int main()
{
function(5);
return 0;
}
В таком случае результатирующая библиотека не содержит ничего связанного с функцией "function".И естественно в результате линковки бинарного файла мы получаем ошибку:
unresolved external symbol "void __cdecl function<int>(int const &)"Если почитать Страструпа то в главе 13.7 упоминается про ключевое слово export, которое должно решать подобные проблемы. Но на данный момент: gcc говорит
warning: keyword 'export' not implemented, and will be ignoredна попытку использовать это слово.
Поэтому засунуть корректно шаблон в cpp не удастся.
Единственное, что можно сделать, это хак. В виде дополнительной функции аппендикса, которая инстанцирует необходимые функции из шаблона функции например:
lib.cpp
...
void a()
{
function(6);
}
Что конечно не лучшее решение, потому как компилятор может "случайно" за inline-ить ваш результат инстанцирования. Но другого метода я пока не нашёл.Больше информации тут (английский): http://cpp.tribe.net/thread/5e706586-7594-4be5-9e69-bf20bbfc5c2f
0 комментария(ев):
Post a Comment