I would like to initialise a struct member with a hash of the struct name.
constexpr uint32_t myHash(const char* const data)
{ //Some code for hash
return myHash;
}
struct My_Struct{
constexpr Test() : ID(myHash("My_Struct"))
{
}
const uint32_t ID;
}
When I have:
constexpr My_Struct my_constexpr_struct;
Then the hash is computed at compile time successfully. However, when I have in my main function
My_Struct my_normal_struct;
then it will call the
constexpr uint32_t myHash(const char* const data)
function in the code instead of simply initialising the struct member with a compile time constant.
This would obviously incur a significant performance penalty that is avoidable.
Any thoughts or suggestions on how to have the compiler perform this at compile time? I don't really want to do:
constexpr uint32_t MY_STRUCT_ID = myHash("My_Struct");
struct My_Struct{
constexpr Test() : ID(MY_STRUCT_ID)
{
}
const uint32_t ID;
Thanks.
constexpr is a request, not a requirement. As such, if you initialize an object outside of a constant expression context, even through a constexpr constructor, there is no guarantee that the initialization will be done at compile time.
If you want to guarantee compile-time evaluation, you have to call the constexpr function it in a constant expression context. If the explicit use of a variable offends you in some way, you could always force constexpr evaluation through the use of a template:
template<typename T, T t>
struct repeat
{
using value_type = T;
static constexpr T value = t;
constexpr T operator()() const noexcept {return t;}
};
struct My_Struct{
constexpr My_Struct() : ID(repeat<uint32_t, myHash("My_Struct")>::value)
{
}
const uint32_t ID;
};
Related
For example I got this code:
constexpr static std::size_t ConstexprFunction(const int value) {
return value;
}
static constexpr std::size_t CallConstexptrFunction(const int value) {
constexpr std::size_t v = ConstexprFunction(value);
return v;
}
int main() {
constexpr int test = 42;
CallConstexptrFunction(test);
}
the compiler will argued that constexpr variable 'v' must be initialized by a constant expression, it looks like the ConstexprFunction is actually run on runtime, not on compile-time. I change the code to this:
static constexpr std::size_t CallConstexptrFunction(const int value) {
constexpr std::size_t v = value;
return v;
}
int main() {
constexpr int test = 42;
CallConstexptrFunction(test);
}
and the error keeps the same, which may prove that when use the value in the CallConstexptrFunction, it is considered to a runtime variable rather than a contexpr variable.
currently my solution is to change the function parameter to a template parameter to avoid parameter passing:
constexpr static std::size_t ConstexprFunction(const int value) {
return value;
}
template<int SIZE>
static constexpr std::size_t CallConstexptrFunction() {
constexpr std::size_t v = ConstexprFunction(SIZE);
return v;
}
there's a similarly question, but the question:
It is based on C++11.
One of the OP's solution makes the function run on runtime, don't know the OP award that or not (the case he called the returned the function directly, not hold the return value by a constexpr variable).
and after reading the question here's my questions:
Will the template version generate too many instances which will lead the code size to be too large?
Can the function parameter passing be done without using template (any version is welcome, even C++20), I tried constexpr int value as parameter and use Clang and C++20 experimental, it seems this syntax is still not allowed.
In context of CallConstexptrFunction, expression ConstexprFunction(value) is not constexpr because of value can possibly have a dynamic lifetime, so initialization of v is illegal.
Proper way would be do something like this
constexpr std::size_t ConstexprFunction(const int value) {
return value;
}
constexpr std::size_t CallConstexptrFunction(const int value) {
return ConstexprFunction(value);
}
int main() {
constexpr int test = 42;
constexpr auto res = CallConstexptrFunction(test);
return res;
}
CallConstexptrFunction(test) in main() is a constexpr expression. So compiler would happily evaluate it, generating something like following code.
mov eax, 42
ret
Suppose I have a struct template S that is parametrized by an engine:
template<class Engine> struct S;
I have two engines: a "static" one with a constexpr member function size(), and a "dynamic" one with a non-constexpr member function size():
struct Static_engine {
static constexpr std::size_t size() {
return 11;
}
};
struct Dynamic_engine {
std::size_t size() const {
return size_;
}
std::size_t size_ = 22;
};
I want to define size() member function in S that can be used as a constexpr if the engine's size() is constexpr. I write:
template<class Engine>
struct S {
constexpr std::size_t size() const {
return engine_.size();
}
Engine engine_;
};
Then the following code compiles with GCC, Clang, MSVC and ICC:
S<Static_engine> sta; // not constexpr
S<Dynamic_engine> dyn;
constexpr auto size_sta = sta.size();
const auto size_dyn = dyn.size();
Taking into account intricacies of constexpr and various "ill-formed, no diagnostic is required", I still have the question: is this code well-formed?
Full code on Godbolt.org
(I tagged this question with both c++17 and c++20 in case this code has different validity in these two standards.)
The code is fine as written.
[dcl.constexpr]
6 If the instantiated template specialization of a constexpr
function template or member function of a class template would fail to
satisfy the requirements for a constexpr function or constexpr
constructor, that specialization is still a constexpr function or
constexpr constructor, even though a call to such a function cannot
appear in a constant expression. If no specialization of the template
would satisfy the requirements for a constexpr function or constexpr
constructor when considered as a non-template function or constructor,
the template is ill-formed, no diagnostic required.
The member may not appear in a constant expression for the specialization that uses Dynamic_engine, but as the paragraph above details, that does not make S::size ill-formed. We are also far from ill-formed NDR territory, since valid instantations are possible. Static_engine being a prime example.
The quote is from n4659, the last C++17 standard draft, and similar wording appears in the latest C++20 draft.
As for the evaluation of sta.size() as a constant expression, going over the list at [expr.const] I cannot find anything that is disallowed in the evaluation itself. It is therefore a valid constant expression (because the list tells us what isn't valid). And in general for a constexpr function to be valid, there just needs to exist some set of arguments for which the evaluation produces a valid constant expression. As the following example form the standard illustrates:
constexpr int f(bool b)
{ return b ? throw 0 : 0; } // OK
constexpr int f() { return f(true); } // ill-formed, no diagnostic required
struct B {
constexpr B(int x) : i(0) { } // x is unused
int i;
};
int global;
struct D : B {
constexpr D() : B(global) { } // ill-formed, no diagnostic required
// lvalue-to-rvalue conversion on non-constant global
};
Yes.
Functions may be marked as constexpr without being forced to be evaluated at compile-time. So long as you satisfy the other requirements for marking a function as constexpr, things are okay (returns a literal type, parameters are literals, no inline asm, etc.). The only time you may run into issues is if it's not actually possible to create arguments that satisfy the function being called as a core constant expression. (e.g., if your function had undefined behavior for all values, then your function would be ill-formed NDR)
In C++20, we received the consteval specifier that forces all calls to the function to be able to produce a compile-time constant (constexpr).
Not a direct answer but an alternative way:
struct Dynamic_Engine
{
using size_type = size_t;
size_type size() const
{
return _size;
}
size_type _size = 22;
};
struct Static_Engine
{
using size_type = std::integral_constant<size_t, 11>;
size_type size() const
{
return size_type();
}
};
template <typename ENGINE>
struct S
{
auto size() const
{
return _engine.size();
}
ENGINE _engine;
};
int main()
{
S<Static_Engine> sta;
S<Dynamic_Engine> dyn;
const auto size_sta = sta.size();
const auto size_dyn = dyn.size();
static_assert(size_sta == 11);
}
I had the same kind of problems and IMHO the easiest and more versatile solution is to use std::integral_constant. Not more needs to juggle with constexpr as the size information is directly encoded into the type
If you still really want to use constexpr (with its extra complications) you can do:
struct Dynamic_Engine
{
size_t size() const
{
return _size;
}
size_t _size = 22;
};
struct Static_Engine
{
static constexpr size_t size() // note: static
{
return 11;
}
};
template <typename ENGINE>
struct S
{
constexpr size_t size() const
{
return _engine.size();
}
ENGINE _engine;
};
int main()
{
S<Static_Engine> sta;
S<Dynamic_Engine> dyn;
constexpr size_t size_sta = sta.size();
const size_t size_dyn = dyn.size();
static_assert(size_sta == 11);
}
#include <type_traits>
template<size_t S> struct A
{
constexpr size_t size() const noexcept { return S; } // Not static on purpose!
};
struct B : public A<123> {};
template <class T>
typename std::enable_if<std::is_base_of_v<A<T().size()>, T>, bool>::type // (*)
f(const T&, const T&) noexcept { return true; }
int main() {
B b1, b2;
f(b1, b2);
}
In my original question in (*) line I mistakenly used T()::size(), which is obviously incorrect since size() is not static.
The code works with T().size() and std::declval<T>().size(). So the question now is what is the difference and if any of these ways are more correct or better?
You didn't specify which compiler you're using, but gcc's error message offers a big honking clue:
t.C:12:52: error: cannot call member function ‘constexpr size_t A<S>::size() const
[with long unsigned int S = 123; size_t = long unsigned int]’ without object
After adjusting the declaration of the method accordingly:
static constexpr size_t size() noexcept { return S; }
gcc then compiled the shown code without issues.
If your intent is really to have size() be a regular class method, then you'll need to use std::declval instead of invoking it as a static method, in your template.
size is a non-static function and requires an object to call. Make it static and remove const.
Here is my code:
template<int... I>
class MetaString1
{
public:
constexpr MetaString1(constexpr char* str)
: buffer_{ encrypt(str[I])... } { }
const char* decrypt()
{
for (int i = 0; i < sizeof...(I); ++i)
buffer_[i] = decrypt1(buffer_[i]);
buffer_[sizeof...(I)] = 0;
return buffer_;
}
private:
constexpr char encrypt(constexpr char c) const { return c ^ 0x55; }
constexpr char decrypt1(constexpr char c) const { return encrypt(c); }
private:
char buffer_[sizeof...(I)+1];
};
#define OBFUSCATED1(str) (MetaString1<0, 1, 2, 3, 4, 5>(str).decrypt())
int main()
{
constexpr char *var = OBFUSCATED1("Post Malone");
std::cout << var << std::endl;
return 1;
}
This is the code from the paper that I'm reading Here. The Idea is simple, to XOR the argument of OBFUSCATED1 and then decrypt back to original value.
The problem that I'm having is that VS 2017 gives me error saying function call must have a constant value in constant expression.
If I only leave OBFUSCATED1("Post Malone");, I have no errors and program is run, but I've noticed that if I have breakpoints in constexpr MetaString1 constructor, the breakpoint is hit, which means that constexpr is not evaluated during compile time. As I understand it's because I don't "force" compiler to evaluate it during compilation by assigning the result to a constexpr variable.
So I have two questions:
Why do I have error function call must have a constant value in constant expression?
Why do people use template classes when they use constexpr functions? As I know template classes get evaluated during compilation, so using template class with constexpr is just a way to push compiler to evaluate those functions during compilation?
You try to assign a non constexpr type to a constexpr type variable,
what's not possible
constexpr char *var = OBFUSCATED1("Post Malone")
// ^^^ ^^^^^^^^^^^
// type of var is constexpr, return type of OBFUSCATED1 is const char*
The constexpr keyword was introduced in C++11, so before you had this keyword you had to write complicated TMP stuff to make the compiler do stuff at compile time. Since TMP is turing complete you theoretically don't need something more than TMP, but since TMP is slow to compile and ugly to ready, you are able to use constexpr to express things you want evaluate at compile time in a more readable way. Although there is no correlation between TMP and constexpr, what means, you are free to use constexpr without template classes.
To achieve what you want, you could save both versions of the string:
template <class T>
constexpr T encrypt(T l, T r)
{
return l ^ r;
}
template <std::size_t S, class U>
struct in;
template <std::size_t S, std::size_t... I>
struct in<S, std::index_sequence<I...>>
{
constexpr in(const char str[S])
: str_{str[I]...}
, enc_{encrypt(str[I], char{0x12})...}
{}
constexpr const char* dec() const
{
return str_;
}
constexpr const char* enc() const
{
return enc_;
}
protected:
char str_[S];
char enc_[S];
};
template <std::size_t S>
class MetaString1
: public in<S, std::make_index_sequence<S - 1>>
{
public:
using base1_t = in<S, std::make_index_sequence<S - 1>>;
using base1_t::base1_t;
constexpr MetaString1(const char str[S])
: base1_t{str}
{}
};
And use it like this:
int main()
{
constexpr char str[] = "asdffasegeasf";
constexpr MetaString1<sizeof(str)> enc{str};
std::cout << enc.dec() << std::endl;
std::cout << enc.enc() << std::endl;
}
This is a continuation of the problem I found and described here.
Say you have a struct that contains a static constexpr function and a type alias for a std::bitset (or any type you wish to template using the result of the const expression) that looks as follows:
struct ExampleStruct {
static constexpr std::size_t Count() noexcept {
return 3U;
}
using Bitset = std::bitset<Count()>;
};
Visual Studio 2015 version 14.0.25029.00 Update 2 RC highlights the Count() call in red and generates the error function call must have a constant value in a constant expression.
How might one get this to compile, or achieve similar results?
What exactly is causing the error here? Is the compiler trying to generate the type alias before the const expression function?
EDIT: The explanation for why this does not work can be found below, but since no one provided possible workarounds, here are some that I came up with:
(1) When using templates, store type alias to this type.
template<typename T>
struct ExampleStruct {
using ThisType = ExampleStruct<T>;
static constexpr std::size_t Count() noexcept {
return 3U;
}
using Bitset = std::bitset<ThisType::Count()>;
};
(2) Move Count() function outside of the struct body.
static constexpr std::size_t Count() noexcept {
return 3U;
}
struct ExampleStruct {
using Bitset = std::bitset<Count()>;
};
(3) Replace constexpr method with constexpr member variable.
struct ExampleStruct {
static constexpr std::size_t Count = 3U;
using Bitset = std::bitset<Count>;
};
(4) Store value in constexpr member variable, and return this from Count() method.
struct ExampleStruct {
private:
static constexpr std::size_t m_count = 3U;
public:
static constexpr std::size_t Count() noexcept {
return m_count;
}
using Bitset = std::bitset<m_count>;
};
You might have noticed that if you move one or both lines outside of the class body, the error goes away. The problem you're running into is that class member function definitions (even inline ones) are not parsed until after the entire class definition has been parsed; therefore, when the compiler sees using Bitset = std::bitset<Count()>;, at that point Count has been declared but not yet defined, and a constexpr function that has not been defined cannot be used in a constant expression -- so you get the error you're seeing. Unfortunately, I know of no good solution or workaround for this.