C++:非内联模板方法的放置

标签 c++ templates include

假设我有一个带有方法模板的类:

//file: X.h
class X{

    int x;
    //... more members and non-template functions

    template<typename T>
    void foo(T t){ //Error, cannot define the method here. Declaration is okay
        Y y = ...;
    }
}

//file Y.h
class Y {
    X x;
}

由于循环类依赖(foo 的主体依赖于 Y,Y 依赖于 X),我无法定义声明它的方法模板 foo (请现在不要质疑设计) .

那么,在这种情况下,将 foo 的定义放在哪里呢?我无法将其放入 .cpp 文件中的其他定义,否则链接将失败。

我的解决方案是创建一个新的头文件,例如“X.hpp”,只将模板方法的定义添加到其中。在此文件中,我包括“X.h”和“Y.h”。现在,每当我需要 X 类时,我只需仅包含“X.hpp”,它将依次包含其他必要的 h 文件。

所以我的问题是:这是正确/最好的方法吗?不知何故,我有一个仅用于单个方法模板定义的 .hpp 文件,但这似乎是在循环类型依赖项的情况下唯一可能的方法。再次请注意:不要通过说“最好避免循环类型依赖”或类似的话来质疑设计。问题是:如果我有这些依赖项,处理单一方法模板的最佳方法是什么。

最佳答案

不质疑设计:

//file: X.h
#ifndef X_H
#define X_H
class X{

    int x;
    //... more members and non-template functions

    template<typename T>
    void foo(T t);
};

#include "Y.h"

template<typename T>
void X::foo(T t){ //Error, cannot define the method here. Declaration is okay
    Y y = ...;
}

#endif


//file Y.h
#ifndef Y_H
#define Y_H

#ifndef X_H
#error "Please include X.h"
#endif

class Y {
    X x;
}

#endif

不需要额外的文件。

关于C++:非内联模板方法的放置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12142292/

相关文章:

c++ - 如何查找给定键是否存在于 C++ std::map 中

c++ - 如何使用 visual studio c 在 win32 中拉伸(stretch)背景图像

javascript - Handlebars 范围问题 : Can't access template variable from embedded `each`

c++ - 如何使模板类成为类的友元?

c++ - 安装位置缺少头文件

c++ - 是否可以从 Visual Studio 2017 创建 Linux 共享库?

android - 在 Android NDK 上将 GNU STL 和 C++11 与 V8 结合使用

c++ - 我想在 C++ 中为 map<> 的给定 KEY 返回一个 VALUE。如果 KEY 不在 map<> 中,返回什么?

r - 在构建 R 包时从另一个 Rcpp 函数调用 Rcpp 函数

C++ 包含 header /前向声明顺序