代码之家  ›  专栏  ›  技术社区  ›  tangy

类型分组模板的显式实例化

  •  2
  • tangy  · 技术社区  · 7 年前

    如果我有一个模板类,其中包含重载的模板成员函数(使用sfinae),比如:

    template <typename T>
    struct Foo{
        Foo(T elem);
    
        template <typename U = T>
        auto get() -> std::enable_if_t<std::is_same_v<U, int>, U>;
        template <typename U = T>
        auto get() -> std::enable_if_t<std::is_same_v<U, bool>, U>;
        T elem_;
    };
    

    现在,在我的cpp文件中,我必须定义并显式实例化:

    template class Foo<int>;
    template int Foo<int>::get<int>();
    template class Foo<bool>;
    template bool Foo<bool>::get<bool>();
    // For all types...T, there will be two statements.
    

    按类型分组的实例化有哪些不同的可能方法-例如:

    GroupedFooInit<int>(); // does both Foo<int> and Foo<int>::get<int>
    GroupedFooInit<bool>(); // similar
    .. and so on.
    

    考虑到我有能力使用C++ 14, 2的解决方案,我可以提出但不希望/类似:
    1。 Macros :可能,但要强烈避免。
    2。 Definition in header, no explicit instantiation needed :可能,但是我正在处理一个巨大的repo,我所处理的文件几乎包含在所有地方-所以如果我以这种方式进行微小的更改,我的构建时间是巨大的。

    Link to Code Snippet

    1 回复  |  直到 7 年前
        1
  •  2
  •   Oliv    7 年前

    您可以通过添加层来解决问题:

    template <typename T>
    struct Foo{
      Foo(T elem);
    
      T elem_;
    
      T get(){
         return do_get<T>();
         }
    
      private:
    
      template <typename U = T>
      auto do_get() -> std::enable_if_t<std::is_same<U, int>::value, U>;
    
      template <typename U = T>
      auto do_get() -> std::enable_if_t<std::is_same<U, bool>::value, U>;
       };
    //If definitions for the do_get functions are provided before these
    //explicit template instantiation definitions, the compiler will certainly
    //inline those definitions.
    template class Foo<int>;
    template class Foo<bool>;