【发布时间】:2017-07-10 13:54:11
【问题描述】:
这是我尝试创建一个简单的 constexpr 链表 -
struct Node
{
constexpr Node(const int n, Node const* next = nullptr)
: value(n), next(next) {}
constexpr Node push(const int n) const { return Node(n, this); }
int value;
Node const* next;
};
constexpr auto getSum(Node n) {
int sum = 0;
Node *current = &n;
while(current != nullptr) {
sum += current->value;
current = current->next;
}
return sum;
}
int main() {
constexpr Node a(0);
a.push(1);
a.push(22);
constexpr auto result = getSum(a);
return result;
}
在编译这个程序时,出现如下错误
prog.cc: In function 'constexpr auto getSum(Node)':
prog.cc:16:28: error: invalid conversion from 'const Node*' to 'Node*' [-fpermissive]
current = current->next;
~~~~~~~~~^~~~
prog.cc: In function 'int main()':
prog.cc:25:35: in constexpr expansion of 'getSum(a)'
prog.cc:16:28: error: conversion of 'const Node*' null pointer to 'Node*' is not a constant expression
我应该如何继续解决这个问题并生成这样的链表?这是Wandbox Link在线查看执行。
【问题讨论】:
-
哇,我不认为你在做什么......
-
constexpr对象仍然遵循抽象机器的规则。所有对push的调用都会返回一个立即过期的临时文件。即使您修复了错误,您的列表也永远不会增加。 -
该死的..这一定是我见过最多的
const和constexpr了..
标签: c++ data-structures c++14 constexpr c++17