我正在开发一个带有一些模板类和方法(几乎只有模板)的 C++ 库。我想拆分声明和实现以便于阅读。但有时它会变得很疯狂:
template < typename T >
class Foo {
template < typename U >
class SubFoo {
};
template < typename U >
SubFoo<U> bar();
};
template < typename T >
template < typename U >
Foo<T>::SubFoo<U> Foo<T>::bar() {}
这是一个非常小的例子...... 所以如果你有一些别名来改进这个,或者任何编码风格指南。 我正在使用 NeoVim,所以如果你知道一些可以让生活更轻松的插件,那也很好。
Ps: 我没有任何c++限制
事实上,我忘记了 C++ 中存在一些基本的东西,比如宏。
#define Class Foo<T>
template < typename T >
template < typename U >
Class::SubFoo<U> Class::bar() {}
不是很好,但还是更好。无论如何没有宏?
最佳答案
I really like the header which describe the class and the source file where you can found the implementation. I think that everything in the same file is a mess
也许您是对的,当您说“同一个文件中的所有内容都是一团糟”时,但是使用模板 结构/类确实很难避免。
下面是一个简单的例子
假设你有三个文件
1) 一个 header (“header.h”),其中定义了一个模板结构 foo
使用已定义但未实现的构造函数
template <typename T>
struct foo
{
foo ();
};
2) 一个带有 main()
的 cpp 文件(“a.cpp”)其中一个 foo<int>
声明了变量
#include "header.h"
int main ()
{
foo<int> fi;
}
3) 一个 cpp 文件(“b.cpp”),其中 foo
构造函数已实现
#include "header.h"
template <typename T>
foo<T>::foo ()
{ }
很好,不是吗?
但是当您编译(我使用 clang++ -c -o a.o a.cpp
和 clang++ -c -o b.o b.cpp
)和链接( clang++ -o a.out a.o b.o
)时,您会在链接阶段出错:对 foo<int>::foo()
的 undefined reference
为什么?
这是因为在编译“b.cpp”时,编译器不知道在“a.cpp”中声明了一个foo<int>
。变量,所以没有实现 foo<int>::foo()
.
是的,您可以明确地告诉编译器,编译“b.cpp”时,它必须实现 foo<int>
所需的内容。 ,修改“b.cpp”如下
#include "header.h"
template <typename T>
foo<T>::foo ()
{ }
template struct foo<int>;
但是当你想使用 foo<long>
在不同的源文件中,您必须记住相应地更新“b.cpp”。
只有当你想控制 foo<T>
的确切类型集时,这是一个很好的解决方案(恕我直言)。可以实现。
通常(恕我直言)最好的解决方案是在 header 中实现所有模板结构/类,并且(恕我直言,像往常一样)在结构/类的主体中实现它更清晰
关于c++ - 需要一些清晰的模板实现代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40947442/