我正在尝试使用非类型模板参数定义模板类。然后我使用这个模板参数确定这个类的成员的类型std::conditional
。我遇到了一些编译时错误。
下面是MWE。在这个 MWE 中,我试图根据条件分别为真(结构化)或假(非结构化)来制作FiniteElementList
模板类的成员 。类 ,包含一些成员和友元函数,这些函数只是暂时声明的,可能会在稍后阶段定义。Mesh
std::vector
std::list
Mesh
MWE
// c++ standard library headers
#include <list> // std::list
#include <type_traits> // std::conditional
#include <vector> // std::vector
// (un)structured flag
enum class StructuredUnstructured { kStructured = true, kUnstructured = false };
// (un)structured mesh
template <StructuredUnstructured is_structured>
class Mesh {
using Element = double;
using FiniteElementList =
typename std::conditional<is_structured ==
StructuredUnstructured::kStructured,
std::vector<Element>, std::list<Element>>::type;
public:
// constructors
Mesh() = default;
Mesh(const Mesh& m) = default; // copy constructor
Mesh(Mesh&& m) noexcept = default; // move constructor
// assignment operators
Mesh& operator=(const Mesh& m) = default; // copy assignment
Mesh& operator=(Mesh&& m) noexcept = default; // move assignment
~Mesh() = default;
void Indexing() {}
void Properties() {}
friend Mesh ReadMesh() {}
friend void WriteMesh() {}
friend void WriteMeshVTK() {}
private:
FiniteElementList finite_elements_{};
};
int main() {
Mesh<StructuredUnstructured::kUnstructured> unstructured;
Mesh<StructuredUnstructured::kStructured> structured;
}
汇编:
我正在尝试使用 clang 编译器进行如下编译
c++ -O3 -Wall -Wextra -Wpedantic -std=c++17 mesh_structure.cpp -o mesh_structure
我遇到了以下错误
mesh_structure.cpp:34:15: error: functions that differ only in their return type cannot be overloaded
friend Mesh ReadMesh() {}
~~~~ ^
mesh_structure.cpp:46:45: note: in instantiation of template class 'Mesh<StructuredUnstructured::kStructured>' requested here
Mesh<StructuredUnstructured::kStructured> structured;
^
mesh_structure.cpp:34:15: note: previous declaration is here
friend Mesh ReadMesh() {}
~~~~ ^
mesh_structure.cpp:36:15: error: redefinition of 'WriteMesh'
friend void WriteMesh() {}
^
mesh_structure.cpp:36:15: note: previous definition is here
mesh_structure.cpp:38:15: error: redefinition of 'WriteMeshVTK'
friend void WriteMeshVTK() {}
^
mesh_structure.cpp:38:15: note: previous definition is here
3 errors generated.
奇怪的是,如果我Mesh<StructuredUnstructured::kStructured> structured;
从main()
函数中删除第二行,代码就会编译。我不太明白这里出了什么问题。任何帮助将不胜感激。
谢谢你。