admin管理员组文章数量:1289382
I really expected this to work:
#include <type_traits>
struct serialiser_deserialiser
{
template <typename U>
void read_or_write(U& obj_to_write)
{
if constexpr (this->isTrue<int>())
{
}
}
template <typename T>
constexpr bool isTrue() const { return true; }
};
int main() {
serialiser_deserialiser serialiser_obj;
int a;
serialiser_obj.read_or_write(a);
}
However the error I get is:
error: constexpr if condition is not a constant expression
What is the reason this isn't a constant expression? Does it have something to do with the fact that it's isTrue() is being called from a templated function? Or that isTrue itself is a templated function?
I really expected this to work:
#include <type_traits>
struct serialiser_deserialiser
{
template <typename U>
void read_or_write(U& obj_to_write)
{
if constexpr (this->isTrue<int>())
{
}
}
template <typename T>
constexpr bool isTrue() const { return true; }
};
int main() {
serialiser_deserialiser serialiser_obj;
int a;
serialiser_obj.read_or_write(a);
}
However the error I get is:
error: constexpr if condition is not a constant expression
What is the reason this isn't a constant expression? Does it have something to do with the fact that it's isTrue() is being called from a templated function? Or that isTrue itself is a templated function?
Share Improve this question edited Feb 20 at 0:26 3CxEZiVlQ 38.9k11 gold badges79 silver badges91 bronze badges asked Feb 20 at 0:21 ZebrafishZebrafish 14.4k3 gold badges64 silver badges152 bronze badges 9 | Show 4 more comments1 Answer
Reset to default 3As to explain why your code is wrong
constexpr
is meant to eliminate all side effects and to have the calculation
doable at compilation time (even though it can also be called during runtime).
As soon as you dereference the non-constexpr this
pointer you depend on a runtime instance, no matter what the method will do.
As @Jarod42 pointed out in the comments:
When you make isTrue
as a static constexpr
method, then you don't need the this
pointer and the expression has no more side effects.
Use
if constexpr (isTrue<int>())
or more explicitly
if constexpr (struct serialiser_deserialiser::isTrue<int>())
本文标签: cWhy isn39t this evaluated as constant expressionStack Overflow
版权声明:本文标题:c++ - Why isn't this evaluated as constant expression? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741464329a2380220.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
serialiser_obj
is not aconstexpr
object – NathanOliver Commented Feb 20 at 0:24if constexpr (this->isTrue<int>())
? :-) What did you try to achive? – Sergey A Kryukov Commented Feb 20 at 0:35