I am attempting to write a linked list of pointer-to-member-functions using constexpr. Mostly for fun but it may have a useful application.
struct Foo;
using MethodPtr = void (Foo::*)();
struct Node
{
constexpr Node(MethodPtr method, const Node* next)
: Method(method)
, Next(next)
{}
constexpr Node Push(MethodPtr method)
{
return Node(method, this);
}
MethodPtr Method;
const Node* Next;
};
struct Foo
{
constexpr static Node GetMethods()
{
return Node{&Foo::Method1, nullptr}
.Push(&Foo::Method2)
.Push(&Foo::Method3);
}
void Method1() {}
void Method2() {}
void Method3() {}
};
int main(void)
{
constexpr Node node = Foo::GetMethods();
}
The above code gives me the following error in main on the call to GetMethods():
const Node{MethodPtr{Foo::Method3, 0}, ((const Node*)(& Node{MethodPtr{Foo::Method2, 0}, ((const Node*)(& Node{MethodPtr{Foo::Method1, 0}, 0u}))}))}' is not a constant expression
Will someone please explain why this is not a constant expression? Or is there an alternate/correct way to achieve the goal of building a list of PTMFs at compile time?
EDIT: I am using the C++ compiler from avr-gcc 4.9.2. I will try this code on another compiler.