C++ Logo

std-discussion

Advanced search

Re: Separate headers for declaration and constexpr definition of the same function

From: Thiago Macieira <thiago_at_[hidden]>
Date: Fri, 02 Jun 2023 13:33:06 -0700
On Friday, 2 June 2023 01:24:11 PDT Lénárd Szolnoki via Std-Discussion wrote:
> I am trying to come up with a pattern that would allow me to have the
> declaration and definition of a constexpr function in separate headers.
> The function would need to be explicitly instantiated in a dedicated
> translation unit.

Use if consteval or if (std::is_constant_evaluated()) and then dispatch to
another function.

> The idea is that users that don't need the constexpr functionality
> could include square.h instead of square_constexpr.h , possibly saving
> some compile time if square_constexpr.h is much heavier (it could
> contain a lot of other additional includes).
>
> Unfortunately doing this with the pattern above is ill-formed, as
> constexpr makes the function implicitly inline[1], and inline functions
> must be defined in the same TU they are used[2], I see no exemptions
> for function templates. Interestingly I merely get a warning in gcc and
> clang, and no warning or error on MSVC. According to [2], this should
> be strictly ill-formed, not IFNDR.

Even if said function is never called?

This compiles:
constexpr int cfunc(int);
constexpr int func(int x)
{
    if consteval {
        return cfunc(x);
    }
    return x;
}

But produces a warning with Clang and GCC. The question is whether the warning
is reasonable because of something the standard says or if we can force the
compilers to shut up.

-- 
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
   Software Architect - Intel DCAI Cloud Engineering

Received on 2023-06-02 20:33:08