1

in C++ is it possible to somehow pass a constant argument through multiple functions and still use consteval functions for them? The code below does not compile to FieldAsInt because the 'key' argument is not a constant,
and I wonder if this can be fixed without changing the function signature (eg FieldAsInt(String, Ptr)) and sill keeping benefits of optimization during compilation of func Resolve

struct MyStruct {
    int Field1;
    double AnotherField;
};
 
constexpr std::tuple<std::string_view, size_t> columns[] = {
    {"Field1", offsetof(MyStruct, Field1)},
    {"AnotherField", offsetof(MyStruct, AnotherField)}
};
 
consteval size_t Resolve(std::string_view columnName) {
    for (const auto& [name, offset] : columns) {
        if (name == columnName) {
            return offset;
        }
    }
    throw std::invalid_argument("Column name not found");
}

int FieldAsInt(std::string_view key, MyStruct* ptr) {
    size_t offset = Resolve(key); // <--- Fails here
    return *reinterpret_cast<int*>(reinterpret_cast<char*>(ptr) + offset);
}
 
int main() {
    MyStruct myStruct{42, 3.14};

    std::cout << "value: " << FieldAsInt("Field1", &myStruct) << std::endl;
 
    return 0;
}
 
4
  • "In C++ is it possible to somehow pass a constant argument through multiple functions..." No, function parameters are not constexpr. Commented Sep 14, 2024 at 8:38
  • @user12002570 are there any workarounds or ways to solve this? Commented Sep 14, 2024 at 9:33
  • It might be possible by changing signature, and call it with FieldAsInt<"Field1">(&myStruct) Commented Sep 14, 2024 at 9:41
  • @Cus You can make it a non-type template parameter which are constexpr. Commented Sep 14, 2024 at 10:58

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.