相关疑难解决方法(0)

开关盒错误 | 的值不可用于常量表达式

我写了一个简单的例子来解决我在写他的程序时遇到的问题。

\n\n

在程序执行期间,当从函数返回值时,我得到 input1 和 input2 的值,这些值永远不会改变。然后稍后,在程序过程中进行各种计算后,我得到一个结果,该结果也不再可变。

\n\n

我正在尝试使用 switch-case 来比较它们,但出现一个错误“\xe2\x80\x98input1\xe2\x80\x99 的值在常量表达式中不可用”。

\n\n
#include <iostream>\n\nusing namespace std;\n\nchar getChar()\n{\n    char c;\n    cin >> c;\n    return c;\n}\n\nint main()\n{\n    // it doesn\'t work\n    const char input1 = getChar();\n    const char input2 = getChar();\n\n    // it it works\n    //const char input1 = \'R\';\n    //const char input2 = \'X\';\n\n    char result = getChar();\n    switch(result)\n    {\n        case input1:\n            cout << "input1" << endl;\n            break;\n        case input2:\n            cout << "input2" << endl;\n            break;\n    }\n    return 0;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

c++ constants switch-statement constexpr c++11

6
推荐指数
1
解决办法
1万
查看次数

constexpr功能的规则

以下示例中:

//Case 1
constexpr int doSomethingMore(int x)
{
    return x + 1;
}

//Case 2
constexpr int doSomething(int x)
{
    return ++x;
}


int main()
{}
Run Code Online (Sandbox Code Playgroud)

输出:

prog.cpp:在函数'constexpr int doSomething(int)'中:
prog.cpp:12:1:错误:表达式'++ x'不是常量表达式

为什么案例1被允许但案例2不被允许?

c++ constexpr c++11

4
推荐指数
1
解决办法
453
查看次数

如何初始化div_t对象?

因此,从div函数返回的成员的顺序似乎是实现定义的.

quot1 成员或者是rem

让我们说我做的是这样的:

generate(begin(digits), end(digits), [i = div_t{ quot, 0 }]() mutable {
    i = div(i.quot, 10);
    return i.rem;
})
Run Code Online (Sandbox Code Playgroud)

当然这里的问题是我不知道我是初始化i.quot还是i.rem在我的lambda捕获中.是否i采用div(quot, 1)唯一的跨平台方式来实现这一目标?

c++ member division modulo

3
推荐指数
2
解决办法
369
查看次数

如果vs constexpr里面的constexpr函数

最近,我修改了一些if constexprif我constexpr功能,发现他们仍然正常工作,并能进行评估时,编译时间.这是一个最小的案例:

template<int N>
constexpr bool is_negative()
{
    if constexpr  (N >= 0) return false;
    else  return true; 
}
int main()
{
    constexpr  bool v = is_negative<1>();
}
Run Code Online (Sandbox Code Playgroud)

live demo

在上面的例子中,N必须在编译时知道因为它是非类型模板参数,所以if constexpr在这里工作正常.然而,这是一个constexpr功能,因此,IIRC,它是可以让即使我更换一个返回值if constexprif:

template<int N>
constexpr bool is_negative()
{
    if  (N >= 0) return false;
    else  return true; 
}
int main()
{
    constexpr  bool v = is_negative<1>();
}
Run Code Online (Sandbox Code Playgroud)

live demo

cppref来看,所有的要求A constexpr function …

c++ compile-time constexpr if-constexpr

3
推荐指数
1
解决办法
306
查看次数

constexpr 函数采用 const char*

我使用 MSVC v141 和/std:c++17.

constexpr const char* test(const char* foo) {
    return foo + 1;
}

constexpr const char* bc = test("abc");
Run Code Online (Sandbox Code Playgroud)

编译得很好,而

constexpr const char* test(const char* foo) {
    constexpr auto bar = foo;
    return bar + 1;
}

constexpr const char* bc = test("abc");
Run Code Online (Sandbox Code Playgroud)

失败:

错误 C2131:表达式未计算为常量

失败是由在其生命周期之外读取变量引起的

注意:参见'foo'的用法

这是正确的行为还是 MSVC 中的错误?

c++ constexpr

0
推荐指数
1
解决办法
86
查看次数