constexpr functions taking references/pointers to volatile objects

65 views
Skip to first unread message

Myriachan

unread,
Aug 23, 2015, 12:50:04 PM8/23/15
to ISO C++ Standard - Discussion
GCC doesn't like the following, saying that lengthof(meow) is not a constant-expression ("has side effects"), but MSVC and Clang accept it:

#include <cstddef>
#include <type_traits>

template <typename T, std::size_t S>
constexpr std::size_t lengthof(const volatile T (&)[S])
{
   
return S;
}

int main()
{
   
volatile int meow[4];
   
static_cast<void>(meow); // shut up warning
   
return static_cast<int>(std::integral_constant<std::size_t, lengthof(meow)>::value);
}

Reading [expr.const], it seems to me that GCC is wrong here, because the only place where volatile is prohibited is in lvalue-to-rvalue conversion, which lengthof(meow) does not do.

Am I right about this?

Melissa

Faisal Vali

unread,
Aug 23, 2015, 10:06:42 PM8/23/15
to std-dis...@isocpp.org
Yes.

Even, this, I believe, is a valid constexpr function, per 5.20:

constexpr int f(int I) {
volatile int L = I; // initialization is not modification,
// and does not entail a l-t-r conversion
// on the lhs per the letter of the standard...
return I;
}

static_assert(f(3) == 3, "");
Reply all
Reply to author
Forward
0 new messages