C++ Logo

std-discussion

Advanced search

constexpr functions and variables

From: Federico Kircheis <federico_at_[hidden]>
Date: Wed, 3 Apr 2024 11:53:50 +0200
Consider following snippet

----
// .hpp file
extern const int myconstant;
// .cpp file
constexpr int fun(){return 42;}
constexpr int myconstant = fun();
----
It is possible to declare a constant variable in a header file, and then 
have it constexpr in the translation unit.
This has following advantages:
  * no init order fiasco
  * can be used in constexpr context in one translation unit
  * no recompilation of other translation units if value changes
  * does not require to put the "dependencies" for creating myconstant 
in the header file
I found myself more than once wanting to write something like
----
// .hpp file
int function(int);
// .cpp file
constexpr int function(int){return 42;}
----
But it is currently not valid C++ (GCC, for example, fails with "error: 
redeclaration 'constexpr int function(int)' differs in 'constexpr' from 
previous declaration")
I would like to write something like that because it has the same 
advantages of myconstant, except for the init-order-fiasco.
A possible workaround is writing
----
// .hpp file
int function(int);
// .cpp file
namespace{
constexpr int function_imp(int){return 42;}
}
int function(int i){
   return function_imp(i);
}
----
but requires some unnecessary boilerplate code, which cannot even be 
automated with a macro, and it gets error prone with functions that 
accepts multiple parameters.
Was such difference between constants and functions considered when 
constexpr did get introduced?
Or was something similar already proposed?
I could not find any relevant information.
Best
Federico

Received on 2024-04-03 09:53:57