Explicit instantiation declaration of header only template(extern template)

心已入冬 提交于 2020-06-24 07:33:12

问题


I am trying to speed up the compile time of the GLM(OpenGL Mathematics). GLM makes heavy usages of C++ templates.

This is what I have tried so far.

math.h
#pragma once

#include <glm\glm.hpp>
extern template struct glm::tvec3<float, glm::highp>;

math.cpp
#include "math.h"
template struct glm::tvec3<float, glm::highp>;

And then I have three files that are using the glm::vec3 template, glm::vec3 is a typedef of glm::tvec3<float, glm::highp>. The three files a,b,c looks almost the same:

a.cpp, b.cpp, c.cpp
#include "math.h"
glm::vec3 func() {
    glm::vec3 a = glm::vec3{1,1,1};
    glm::vec3 b = glm::vec3{1,1,1};
    return a + b;
}

I am using both explicit instantiation definition and explicit instantiation declaration. So the files a,b,c should not cause implicit instantiation. But the compile time is the same as if I don´t do it.


回答1:


Your math.h still causes users to include <glm\glm.hpp>
That's the thing you want to avoid to speed things up. To speed things up, make your own class whose implementation (inside math.cpp) might use glm.hpp, but the users of that class do not need to include glm.hpp themselves.

This is an example left to the student, but you want something like:

math.h
struct vec3{ double x1,x2,x3};
vec3 plus(const vec3& a, const vec3& b);

Then when a.cpp includes math.h, it provides the functions you need, but does not make all your compilation units include glm.hpp.



来源:https://stackoverflow.com/questions/41872632/explicit-instantiation-declaration-of-header-only-templateextern-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!