2017-10-12 123 views
0

我想写一个简单的编译时间尺寸分析库。我想创建一个编译选项来删除库中的所有内容,而无需更改代码。所以基本上我做了我自己的基本类型的版本,并且想要将它们替换为实际的基本类型(如果选择该选项的话)。用原始类型替换模板类

这个代码的最小工作示例

#include <iostream> 
#include <stdint.h> 

#define DEBUG 
#ifdef DEBUG 
    template<int lenght, int time, int mass, int charge, int temperature, int amount, int intensity> 
    struct Dimensions { 
     static const int64_t LENGHT = lenght; 
     static const int64_t TIME = time; 
     static const int64_t MASS = mass; 
     static const int64_t CHARGE = charge; 
     static const int64_t TEMPERATURE = temperature; 
     static const int64_t AMOUNT = amount; 
     static const int64_t INTENSITY = intensity; 
    }; 

    typedef Dimensions< 0, 0, 0, 0, 0, 0, 0 > Adimensional; 
    typedef Dimensions< 1, 0, 0, 0, 0, 0, 0 > Length; 
    typedef Dimensions< 0, 1, 0, 0, 0, 0, 0 > Time; 

    template<typename Dims> class Int32 { 
    private: 
     int32_t m_value; 

    public: 
     inline Int32() : m_value(0) {} 

     inline Int32(int32_t value) : m_value(value) {} 

     inline int32_t value() { 
      return m_value; 
     } 
    }; 

    template<typename Dims> 
    Int32<Dims> inline operator+(Int32<Dims> &lhs, Int32<Dims> &rhs) { 
     return Int32<Dims>(lhs.value() + rhs.value()); 
    } 

    struct Unmatched_dimensions_between_operands; 

    template<typename DimsLhs, typename DimsRhs> 
    Unmatched_dimensions_between_operands inline operator+(Int32<DimsLhs> &lhs, Int32<DimsRhs> &rhs); 
#else 
    template<typename Dims> using Int32<Dims> = std::int32_t; 
#endif 

int main(int argc, char* argv[]) { 
    Int32<Time> a = 2; 
    Int32<Time> b = 5; 

    std::cout << (a + b).value() << "\n"; 
    return 0; 
} 

当我删除了#define DEBUG线我得到的编译错误

Error C2988 unrecognizable template declaration/definition 59 

是否有替换的Int32任何模板版本有道具有原始类型的代码?

+2

“没有工作”*什么都不起作用?你得到了什么错误?* –

+0

并且不要椭圆化整个基本展示...... –

+0

但是......'Int32'是一个模板类型? Int32的'Dims'是什么?如果'Int32'是一个简单的(无模板)类型,那么'使用Int32 = std :: int32_t'呢? – max66

回答

1

尝试:

template<typename Dims> using Int32 = std::int32_t; 

你也需要定义Time(可能AdimensionalLength)不知何故(不要紧如何,作为模板参数从未使用过)。

编辑:您的程序仍然不会运行,因为您访问的成员valueInt32当然这不在std::int32_t中。不过,我希望这能让你走上正轨。

+0

非常感谢!它的工作,但我不明白为什么它的作品。为什么'Int32'上的模板不明确? – mbtg

+0

别名模板定义如下所示:template using Alias = Foo ; – Knoep

+0

就你而言,你根本就没有使用模板参数。 – Knoep