C++ 如何在源文件中专门化模板函数?
我们在开发发动机时遇到了这个问题。我们想要C++ 如何在源文件中专门化模板函数?,c++,templates,template-specialization,specialization,C++,Templates,Template Specialization,Specialization,我们在开发发动机时遇到了这个问题。我们想要 template <typename T> std::pair<const uint8_t*, size_t> get_resource() { return {nullptr, 0ull}; } 模板 std::pair get_资源() { 返回{nullptr,0ull}; } 并专门为许多Ts。最重要的是,我们希望专门化活在单独的源(.cpp)文件中,并编译到引擎的静态库二进制文件中。在源文件中放置专门化是至
template <typename T>
std::pair<const uint8_t*, size_t> get_resource()
{
return {nullptr, 0ull};
}
模板
std::pair get_资源()
{
返回{nullptr,0ull};
}
并专门为许多
T
s。最重要的是,我们希望专门化活在单独的源(.cpp
)文件中,并编译到引擎的静态库二进制文件中。在源文件中放置专门化是至关重要的,因为这些函数可能会被频繁更改,并被引擎的巨大代码库(至少几十万LoC)的其他头文件包含在内。因此,如果它们存在于头文件中,则在更改某个专门化定义时,可能会导致重建项目的大部分。对于这样一个问题,我找不到帮助,所以我在这里发布了我们的解决方案。首先:在源文件中放置函数模板专门化是没有问题的,因为当专门化时,它就像其他函数一样。棘手的是让源#包含并使用模板定义定义存在这种专门化的标题。显然,C++中没有办法声明专门化。您可以做的是强制实例化某些T
的get\u resource
模板(显然我们无论如何都需要这样做,因为我们希望将专门化编译成库二进制文件)。这可以通过以下语法完成:
//force instantiation of get_resource for T=SOME_TYPE
template std::pair<const uint8_t*, size_t> get_resource<SOME_TYPE>();
源文件
template<> std::pair<const uint8_t*, size_t> get_resource<SOME_TYPE>()
{
return {reinterpret_cast<const uint8_t*>("whatever"), 9ull};
}
template std::pair<const uint8_t*, size_t> get_resource<SOME_TYPE>();
template std::pair get_resource()
{
返回{reinterpret_cast(“任意”),9ull};
}
模板std::pair get_resource();
不是重复的答案,但这个答案可能就是您得出的答案。
template<> std::pair<const uint8_t*, size_t> get_resource<SOME_TYPE>()
{
return {reinterpret_cast<const uint8_t*>("whatever"), 9ull};
}
template std::pair<const uint8_t*, size_t> get_resource<SOME_TYPE>();