Skip to content

read of non-constexpr variable 'a' is not allowed in a constant expression #3

@chlict

Description

@chlict

源代码:

template<typename T>
struct A {
    T data;

    constexpr A(const T &data) : data(data) {}

    constexpr A(T &&data) : data(data) {}

    constexpr T getData() {
        return data;
    }
};

template <typename T>
struct B {
    T x;

    constexpr B(T x) : x(x) {}

    // constexpr B(const B &other) : x(other.x) {}
};

TEST(Suite1, Test3) {
    auto a = A(B(1_c));
    static_assert(a.data.x == 1_c);
    static_assert(a.getData().x == 1_c);
}

编译出错:

/Users/chenlong/software/TensorExamples/test/test.cpp:32:19: error: static_assert expression is not an integral constant expression
    static_assert(a.getData().x == 1_c);
                  ^~~~~~~~~~~~~~~~~~~~
/Users/chenlong/software/TensorExamples/src/includes/Test.hpp:12:16: note: read of non-constexpr variable 'a' is not allowed in a constant expression
        return data;
               ^
/Users/chenlong/software/TensorExamples/src/includes/Test.hpp:12:16: note: in call to 'B(a.data)'
/Users/chenlong/software/TensorExamples/test/test.cpp:32:21: note: in call to '&a->getData()'
    static_assert(a.getData().x == 1_c);
                    ^
/Users/chenlong/software/TensorExamples/test/test.cpp:30:10: note: declared here
    auto a = A(B(1_c));
         ^
1 error generated.

注意:

  1. a.data可以用于static_assert而a.getData()不可以
  2. struct B中打开注释的一行就能编译通过

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions