mercredi 4 novembre 2020

Why are `const` pointers to functions not usable in a constant expression?

Consider the following template:

using IntFnPtr = int(*)(int);
template <IntFnPtr> void f() { }

And these tests:

int g(int) { }

int main()
{
    f<&g>(); // OK

    const IntFnPtr cp = &g;
    f<cp>(); // Error -- why? 

    constexpr IntFnPtr cexprp = &g;
    f<cexprp>(); // OK
}

Why is the attempt to instantiate f with cp ill-formed? The compiler complains about:

> error: no matching function for call to 'f'

live example on godbolt.org


Note that this seems inconsistent with other entities, such as integers:

template <int> void f() { }

int main()
{
    f<5>(); // OK

    const int ci = 5;
    f<ci>(); // OK

    constexpr int cexpri = 5;
    f<cexpri>(); // OK
}

Aucun commentaire:

Enregistrer un commentaire