【问题标题】:Replacing template class by primitive types [closed]用原始类型替换模板类[关闭]
【发布时间】:2017-10-12 23:00:30
【问题描述】:

我正在尝试编写一个简单的编译时维度分析库。我想创建一个编译选项来删除库所做的一切而不更改代码。所以基本上我制作了自己的原始类型版本,如果选择了该选项,我想用实际的原始类型替换它们。

这是代码的最小工作示例

#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 的任何模板版本替换为原始类型?

【问题讨论】:

  • “没用” 什么没用?你遇到了什么错误?
  • 并且不要省略整个重要的说明......
  • 但是... Int32 是模板类型? Int32Dims 是什么?如果Int32 是简单(无模板)类型,那么using Int32 = std::int32_t 呢?
  • 抱歉信息不足,我编辑了问题并添加了类和维度类型。
  • 请尽量使这个完整但最小的例子。阅读可以提供给编译器以生成错误的代码。

标签: c++ templates using type-alias


【解决方案1】:

试试:

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

您还需要以某种方式定义Time(可能还有AdimensionalLength)(不管如何,因为从不使用模板参数)。

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

【讨论】:

  • 非常感谢!它起作用了,但我真的不明白它为什么起作用。为什么Int32上的模板不明确?
  • 别名模板定义如下所示: template using Alias = Foo;
  • 在您的情况下,您根本没有使用模板参数。
猜你喜欢
  • 2011-03-14
  • 1970-01-01
  • 1970-01-01
  • 2018-09-11
  • 2011-11-20
  • 1970-01-01
  • 2011-02-13
  • 1970-01-01
  • 2013-10-04
相关资源
最近更新 更多