Why is this not a constant expression?

后端 未结 4 1326
广开言路
广开言路 2021-01-01 12:21

In this trivial example, test2 fails to compile even though test1 succeeds, and I don\'t see why that is the case. If arr[i] is suitab

4条回答
  •  清酒与你
    2021-01-01 13:12

    There's a misconception of what constexpr does here. It indicates that a function must be evaluatable at compile time for suitable arguments, but it does not remove the requirement still to compile in the general case.

    Let's take the first version:

    template 
    constexpr char test1(const char (&arr)[N], unsigned i) {
        return arr[i];
    }
    

    Now, this is clearly a compile-time evaluation:

    enum { CompileTimeConstant = test1("Test", 0) };
    

    your example may be, but it's an optimizer/QoI issue:

    char MayBeCompileTimeConstant = test1("Test", 0);
    

    and this example obviously isn't, but is still required to be evaluatable

    char arr[10];
    int i;
    std::cin >> i;
    std::cin >> arr;
    char b = test1(arr, i);
    std::cout << "'" << arr << "'[" << i << "] = " << b << '\n';
    

    Since test2 can't possibly compile in for the last case, it can't compile at all. (Please note I'm not suggesting that code is good).

提交回复
热议问题