Cpp-based Expression

The difficulty is that the string expected by the Python Expression constructor is something that you should be able to paste in as an R-value to complete values[0] = ... , not a full definition of a C++ Expression subclass. For the conditional logic you have in your class’s eval method, you can compress it all into one line of C++ with the ternary operator, as follows:

from fenics import *

mesh = UnitSquareMesh(8, 8)
V0 = FunctionSpace(mesh, 'DG', 0)

funcstring = """((x[0] >= 0.25 && x[0] < 0.5))?
                 ((x[1] >= 0.5 && x[1] < 0.625)?
                   1.0 : ((x[1] >= 0.625 && x[1] < 0.75)? 
                          -1.0 : 0.0)) : 0.0;"""
function = project(Expression(funcstring, degree=0), V0)

from matplotlib import pyplot as plt
plot(function)
plt.show()

If you really do need to define a C++ Expression subclass, I think the way to go would be something more like what @miguel did with SubDomain here, using pybind11 and compile_cpp_code: