c++ - 在这种情况下,可以在 cpp 文件中编写模板特化吗?

标签 c++ template-specialization

假设我的代码结构是这样的:

  • header1.h

    template <class T, template<class> class C>
    struct metafunction {
        using type = typename C<T>::type; 
    };
    
    inline namespace msn {
        template <class T> struct implementation; 
    }
    
    // uses the *implementation* not defined in the header!
    template <class T>
    struct use_case {
        using type = typename metafunction<T, implementation>::type; 
    }; 
    
  • cpp1.cpp

    #include <header1.h>
    
    // I'll only need this in this compilation unit, so the
    // question is:    "Is this a good place to define it?"
    template <>
    struct implementation<int> {
        using type = int; 
    }; 
    
    int main() {
        using tt = int; 
        // is this point of instantiation OK due to 
        // the existence of a specialization in the same cpp file? 
        using tt = use_case<int>::type; 
    
        tt var; 
        (void)var; 
    }
    

我的先决条件是我将只使用 cpp 文件中的特定特化,因此我不必处理链接器问题。 我知道这不适用于 cpp2.cpp文件包括 header1.h并试图只使用 use_case<int>或重新定义 implementation<int>违反 ODR。所以我要问的是这段代码是否类似于它的linear form (一个版本,其中所有内容都以一致的顺序放入单个 cpp 文件中),(显然)编译得很好。

最佳答案

是的,只要它只在同一个翻译单元中使用,它就是格式正确的。

请记住,#include 的效果就像引用的文件被逐字插入到翻译单元中一样。

这就是 #include 的含义。

由此,我们可以得出几个结论:

每个 C++ 翻译单元都是一个虚拟文件。

因此,格式良好的翻译单元中的每个特化都在定义它的同一翻译单元中被引用。

Q.E.D.

关于c++ - 在这种情况下,可以在 cpp 文件中编写模板特化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39359229/

相关文章:

c++ - 从拥抱类型中获取模板参数的值

c++ - 从 QFileSystemModel 中的文件路径和文件名获取 QModelIndex

c++ - 模板特化 : Can we partially implement the special cases

c++ - cpp 模板特化,错误说参数 1 的类型是 T,这取决于参数 T

c++ - enable_if 用于类模板特化,参数不是 void

c++ - 模板类中的模板成员函数特化

c++ - 结构体变量名称的含义是什么?

c++ - std::numeric_limits<T>::digits 应该代表什么?

c++ - 给定一定的固定平台,sizeof 是否可以为同一类型返回不同的大小?

c++ - 仅在模板中专门构造函数,保持最佳性能和整洁的界面