小编Nax*_*im'的帖子

使用预处理器的良好实践声明多个类似的类?

假设我想创建一个数学库.我需要处理的载体在不同的维度,所以我想有每个维度中的一个类(又名Vector2,Vector3,Vector4...)

到现在为止还挺好.但它会导致严重的代码重复,因为Vector3主要是某些函数中Vector2使用的z属性.

所以我有个主意.代码复制是机器而不是人类的任务,所以我可以这样写:

在Vector.hpp中:

#ifndef VECTOR_HPP
#define VECTOR_HPP

#define VECTOR_DIM 2
#include "_Vector.hpp"
#define VECTOR_DIM 3
#include "_Vector.hpp"
#define VECTOR_DIM 4
#include "_Vector.hpp"
#undef VECTOR_DIM

#endif
Run Code Online (Sandbox Code Playgroud)

在_Vector.hpp中:

// This header was not protected from multiple inclusions on purpose

#define VECTOR_NAME Vector ## VECTOR_DIM

class VECTOR_NAME
{
public:
    // Some methods here ...

    float x;
    float y;
#if VECTOR_DIM >= 3
    float z;
#endif
#if VECTOR_DIM >= 4
    float …
Run Code Online (Sandbox Code Playgroud)

c++ c-preprocessor

2
推荐指数
1
解决办法
159
查看次数

标签 统计

c++ ×1

c-preprocessor ×1