C++ Logo

std-discussion

Advanced search

Re: constexpr functions and variables

From: Tiago Freire <tmiguelf_at_[hidden]>
Date: Wed, 3 Apr 2024 15:43:12 +0000
Actually, you could do it even better.
As long as Mylib.cpp doesn’t see:
int function();
you can even just do in myuser.cpp
int function();
int testval = function();

I’m experimenting with other existing ways to force the emission of the function other that defining an assignment to a static function pointer, but it works.


From: Tiago Freire <tmiguelf_at_[hidden]>
Sent: Wednesday, April 3, 2024 17:11
To: Barry Revzin <barry.revzin_at_[hidden]ail.com>; std-discussion_at_[hidden]
Subject: RE: [std-discussion] constexpr functions and variables

No sorry, I take it all back.

What the OP wants to do kind of already works right now in gcc and MSVC.

This is what you do:
Mylib.cpp file you do the following:

constexpr int function()
{
      return 42;
}

On myuser.cpp file you do this:

constexpr int function();
int testval = tfunction();

The issue with this because, function is constexpr the compiler never actually emits the function.
But if you force it to emit the function by adding the following to the “Mylib.cpp” file

static int (*_GARBAGE_OUT_temp)() = function;

And then you suppress all the warnings so that the code compiles. This actually works.
I guess the only thing that you need is to tell the compiler to force it to emit the function.

It is not part of the standard for sure. You could add it so that you don’t have to jump trough these hoops to get the behavior.

>While I agree with (d), I'm not sure what about modules "fix" this?
Modules allows you to just grab the function without needing to see everything else.

If you define it as:
constexpr int function()
or just
int function()

it would be just syntactical without much in the way of any real consequence that you would care about, other than the fact that constexpr also allows you to use it a compile time, which imo is better.
If you could declare it constexpr, why wouldn’t you?

Received on 2024-04-03 15:43:15