首页 > 解决方案 > 自动化显式模板实例化

问题描述

为了减少模板繁重的项目中的编译时间,我试图在单独的编译单元中显式实例化许多模板。因为这些模板依赖于enum class成员,所以我能够列出所有可能的实例。我希望所有其他 cpp 文件只看到声明。虽然我能够做到这一点,但我在尝试分解显式实例时遇到了问题。我将首先解释下面的 2 个工作示例,以解释我的问题到底是什么(示例 3):

示例 1

/* test.h
   Contains the function-template-declaration, not the implementation.
*/

enum class Enum
{
    Member1,
    Member2,
    Member3
};

struct Type
{
    template <Enum Value>
    int get() const;
};
/* test.cpp
   Only the declaration is visible -> needs to link against correct instantiation.
*/

#include "test.h"

int main() {
    std::cout << Type{}.get<Enum::Member1>() << '\n';
}
/* test.tpp 
   .tpp extension indicates that it contains template implementations.
*/

#include "test.h"

template <Enum Value>
int Type::get() const
{
    return static_cast<int>(Value); // silly implementation
}
/* instantiate.cpp
   Explicitly instantiate for each of the enum members.
*/

#include "test.tpp"

template int Type::get<Enum::Member1>() const;
template int Type::get<Enum::Member2>() const;
template int Type::get<Enum::Member3>() const;

如前所述,上面的编译和链接没有问题。然而,在实际应用中,我有很多函数模板和更多枚举成员。因此,我尝试通过将成员分组到一个新类中来使我的生活更轻松,该类本身取决于模板参数并为每个枚举值显式实例化该类。

示例 2

// instantiate.cpp

#include "test.tpp"

template <Enum Value>
struct Instantiate
{
    using Function = int (Type::*)() const;
    static constexpr Function f1 = Type::get<Value>;
   
    // many more member-functions
};

template class Instantiate<Enum::Member1>;
template class Instantiate<Enum::Member2>;
template class Instantiate<Enum::Member3>;

这仍然有效(因为为了初始化指向成员的指针,必须实例化该成员),但是当枚举成员的数量很大时,它仍然会很乱。现在我终于可以解决这个问题了。我想我可以通过定义一个依赖于参数包的新类模板来进一步分解,然后它从包中的每个类型派生,如下所示:

示例 3

// instantiate.cpp

#include "test.tpp"

template <Enum Value>
struct Instantiate { /* same as before */ };

template <Enum ... Pack>
struct InstantiateAll:
    Instantiate<Pack> ...
{};

template class InstantiateAll<Enum::Member1, Enum::Member2, Enum::Member3>; 

这应该有效,对吧?为了实例化,必须实例化InstantiateAll<...>每个派生类。至少,这是我的想法。以上编译但会导致链接器错误。在检查instantiate.owith的符号表后nm,可以确认根本没有实例化任何内容。为什么不?

当然,我可以通过使用示例 2 得到,但这真的让我很好奇为什么事情会这样崩溃。

(使用 GCC 10.2.0 编译)

编辑:在 Clang 8.0.1 上也会发生同样的情况(尽管我必须在分配函数指针时明确使用操作符地址Function f1 = &Type::get<Value>;:)

编辑:用户 2b-t 请通过https://www.onlinegdb.com/HyGr7w0fv_提供示例供人们试验。

标签: c++templatesmetaprogrammingtemplate-meta-programmingexplicit-instantiation

解决方案


如果编译器发现没有引用该代码,即使对于具有副作用的静态初始化,它也可以消除它,我认为您的示例就是这种情况。它可以“证明”那些类实例没有被使用,因此副作用就消失了。

对于非标准解决方案,但适用于 g++(可能是 clang,但未经测试)的解决方案是使用“used”属性标记您的静态数据成员:

template <Enum Value>
struct Instantiate
{
    using Function = int (Type::*)() const;
    static constexpr Function f1 __attribute__((used)) = &Type::get<Value>;
   
    // many more member-functions
};

更新

回顾标准,措辞似乎完全倒退了:

“如果静态存储持续时间的对象具有初始化或具有副作用的析构函数,则即使它看起来未使用也不应被消除,除非可以按照...中的规定消除类对象或其副本。”

所以几十年来我一直在想这个,现在我不确定我在想什么。:) 但它似乎相关,因为属性有帮助。但现在我必须了解发生了什么。


推荐阅读