I have a program which depends on the result of std::is_same_v <const value_t, decltype(value)>
. However, I have found that when functions are passed to this expression the result is unexpected, causing me bugs.
I thought that functions returning const value_t
were going to be treated as being the same as const value_t
, but this seems not to be the case since std::is_same_v <value_t, decltype(func())>
is what returns true.
I tried returning this values using std::as_const, using static_cast, returning it from a constexpr function, but none of them worked as expected.
A minimal, reproducible example:
#include <type_traits>
#include <iostream>
inline const int x = 1;
/// A constant integer variable.
inline const int y() {return x;}
/// A constant integer function returning <x>.
int main()
{
/// <x> successfully passes as being a constant.
std::cout << std::is_same_v <const int, decltype(x)> << " ";
/// But returning it from a function (<y>) does not.
std::cout << std::is_same_v <const int, decltype(y())> << std::endl;
}
Why is this the case? How can I ensure that std::is_same_v <const value_t, decltype(value)>
and std::is_same_v <const value_t, decltype(func())>
both return true?
int r = y();
even withauto r = y();
r is anint
. – Astragalusint f(int)
isint(int)
that is the type of the function. – Buhlerconst
by value is usually pointless (and ignored). If you make thatconst int&
instead and checkis_same
you would see that it's isconst int&
– Bersagliereconst int
should only be seen as a specification that means that I want my function to be treated as it is returning a constant value. – Ginconstexpr
/consteval
would be a better fit in that case. – Bersaglierestruct cx{ const int x; cx(const int x): x(x){ } }; inline cx y() {return x;}
– Astragalusconst
on the return type does not indicate that the function is pure or constant or anything like that. There is currently no way to indicate these properties in the standard language properly. Compilers typically have attributes as extensions to convey these properties. The closest standard feature would probably be theconsteval
qualifier, which indicates that the function must always return the same value for same inputs and must be computed at compile-time. – Urias