[英]is it possible to compile c++ class template instances?
假设我编写了一个类模板,例如Vector<typename T>
。 我想using fvec = Vector<float>;
公开using fvec = Vector<float>;
并using dvec = Vector<double>;
给我的客户
理想情况下,我不希望我的客户知道模板Vector
是如何实现的,或者更好的是,他们只需要知道fvec
和dvec
以及预编译文件的存在即可。
如果您只想为客户端提供头文件,而仅针对double和float交付实现,则可以将模板类显式实例化为cpp文件。
http://en.cppreference.com/w/cpp/language/class_template
例如,您在cpp文件中需要这样的内容
template class Vector<float>;
template class Vector<double>;
为了方便使用,您还可以在h文件中执行一些typedef-这是因为有人可能会决定使用“四重”类型(libquadmath)
另外,您可以在继承自模板的h文件中创建更多clase,但这与typedefs相同。
这是一个构建并运行的简单程序。 类模板Foo
的实现隐藏在Foo.cc中。
oo
#pragma once
template <typename T> class Foo
{
public:
Foo();
void test();
};
template class Foo<float>;
template class Foo<int>;
Foo.cc
#include "Foo.h"
#include <iostream>
template <typename T> Foo<T>::Foo()
{
}
template <typename T> void Foo<T>::test()
{
std::cout << "Came to Foo<T>::test\n";
}
main.cc
#include "Foo.h"
int main()
{
Foo<int> f1;
f1.test();
Foo<float> f2;
f2.test();
// Uncommenting these lines results in linker error.
// Foo<double> f3;
// f3.test();
}
建立命令:
g++ -Wall -std=c++11 Foo.cc main.cc -o program
我也可以使用以下命令进行构建:
g++ -Wall -std=c++11 -c Foo.cc
g++ -Wall -std=c++11 -c main.cc
g++ -Wall -std=c++11 Foo.o main.o -o program
您可以运送Foo.h和包含Foo.o的库。 您的客户将只能使用Foo<int>
和Foo<float>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.