,c++,class,templates"/>

首页 > 解决方案 > 非类型模板参数不是常量表达式 Number

问题描述

我的代码中有以下问题。我正在尝试创建一个变量 num,使用 std::cin 询问用户,然后将其传递给我的模板。但它说“非类型模板参数不是常量表达式”指向模板中的变量 num 。我试过使用“int num”、“const int num”和“const static int num”,但没有人工作。任何想法?

我试过的:

    int num; // no
    static int num; // one 
    const static int num = 0; // works
    std::cin >> num;
    Number<num, num, int> N1(10); // here
    Number<16, 3, int> N2(10);
    std::cout << N1 + N2;

主要代码:

 #include <stdio.h>
 #include <iostream>

 #include <cerrno>
 #include <exception>

 #include "number.hpp"



 int main()
 {
     try
     {
         int num; // Here..

         std::cin >> num;

         Number<num, num, int> N1(10); // Here..
         Number<16, 3, int> N2(10);

         std::cout << N1 + N2;

         N1.suma(N2).write(std::cout);

         std::cout << N1 * N2;

     }
     catch (const std::system_error &e)
     {
         std::cerr << e.what() << '\n';
     }
 }

这是课程:

#include <stdio.h>
#include <iostream>
#include <fstream>

#include <vector>
#include <math.h>

#include <exception>
#include <cerrno> 

template <size_t B, size_t N, typename T = char> // here is the template
class Number
{

private:
  T main_number = NULL;
  void toBase(int valor);

public:
  std::vector<T> v; // Vector que contendrá el numero desglozado

   Number(int valor); // Constructor
  ~Number();

  Number<B, N, T> operator+(const Number<B, N, T> &operando);
  Number<B, N, T> operator-(const Number<B, N, T> &operando);
  Number<B, N, T> operator*(const Number<B, N, T> &operando);

  Number<B, N, T> suma(const Number<B, N, T> &sumando) const;
  Number<B, N, T> resta(const Number<B, N, T> &sumando) const;
  Number<B, N, T> producto(const Number<B, N, T> &sumando) const;

  std::ostream &write(std::ostream &os) const;
  friend std::ostream &operator<<(std::ostream &, Number<B, N, T> &);
};

谢谢!

标签: c++classtemplates

解决方案


推荐阅读