Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
chlict opened this issue Feb 24, 2020 · 0 comments

Comments

@chlict
Copy link
Owner

chlict commented Feb 24, 2020

源代码:

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中打开注释的一行就能编译通过
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant