首页 > 解决方案 > 表达式必须有一个常量值

问题描述

我遇到了麻烦,无法解决,有人可以帮我吗,如果你能解释一下错误,请

template<unsigned long x>
struct dis
{
    dis() { std::cout << x << std::endl; }
};
unsigned int bina(unsigned long x)
{
    return x == 0 ? 0 : x % 10 + 2 * bina(x / 10);
}
int main()
{
    unsigned long b;
    std::cout << "Give a binary number:";
    std::cin >> b;
    dis<bina(b)>out; //here's the error
    return 0;
}

错误是: expr 必须有一个 const 值

标签: c++

解决方案


b不是一个常量表达式,所以bina(b)也不是。

您可能会更改dis为接受运行时值:

struct dis
{
    dis(unsigned long x) { std::cout << x << std::endl; }
};

constexpr unsigned int bina(unsigned long x)
{
    return x == 0 ? 0 : x % 10 + 2 * bina(x / 10);
}
int main()
{
    unsigned long b;
    std::cout << "Give a binary number:";
    std::cin >> b;
    dis /*out*/(bina(b));
    return 0;
}

推荐阅读