【问题标题】:Does this work to reduce compile time for free template functions?这是否可以减少免费模板函数的编译时间?
【发布时间】:2012-06-14 14:10:52
【问题描述】:

我有一个 Visual Studio 2008 c++03 项目,我遇到过这样的事情:

//foo.hpp
namespace Foo {
    template< typename T >
    inline void foo( T t )
    {
        // do stuff...
    };
}; // namespace foo

// foo.cpp
#include "foo.hpp"
namepsace Foo {
    template void foo< int >();
}; // namespace Foo

//main.cpp
#include "foo.hpp"
int main(void)
{
    int a = 5;
    Foo::foo(a);
    return 0;
}

这确实创建了一个我认为包含 Foo::foo&lt; int &gt;() 的 foo.obj 文件,但它似乎不会影响 main.obj 的大小。

这种技术是否可以减少模板代码的编译时间?还是实际上增加了编译时间,因为Foo::foo&lt; int &gt;() 现在必须编译两次?

谢谢

【问题讨论】:

  • 似乎没有意义,因为函数是inline

标签: c++ templates compile-time


【解决方案1】:

如果您不关心函数的内联(编译器可能会覆盖),您可以执行以下操作。它并不完美,但您将有真正的机会改进编译时间。

//foo.hpp
namespace Foo {
    template< typename T >
    void foo( T t );
}; // namespace foo

// foo.cpp
#include "foo.hpp"
namespace Foo {
    template< typename T >
    inline void foo( T t )
    {
        // do stuff...
    };
}; // namespace foo

namespace Foo {
    template void foo< int >();
}; // namespace Foo

//main.cpp
#include "foo.hpp"
int main(void)
{
    int a = 5;
    Foo::foo(a);
    return 0;
}

【讨论】:

    【解决方案2】:

    在功能上没有区别。 foo.cpp 仅包含声明(无定义)。如果在编译中包含foo.cpp,编译时间会增加。

    【讨论】:

      【解决方案3】:

      简短的回答是。 要提高编译速度,您应该这样做:

      //foo.hpp
      namespace Foo {
          template <typename T> void foo( T t );
      
          template <> void foo<int>(int t);
      }; // namespace foo
      
      // foo.cpp
      #include "foo.hpp"
      namepsace Foo {
          template <> void foo<int>(int t)
          {
              // do stuff...
          };
      }; // namespace Foo
      
      //main.cpp
      #include "foo.hpp"
      int main(void)
      {
          int a = 5;
          Foo::foo(a);
          return 0;
      }
      

      【讨论】:

      • 我不明白您为什么觉得需要添加“外部模板”声明。
      • 我的意思是说你根本不需要声明!
      • @Benoît 是的。编译器/链接器不需要此声明。但我认为这个声明是针对开发者的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-08
      • 1970-01-01
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多