Cus
Cus

Reputation: 121

Pass const expression to consteval function through non-consteval functions

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;
}
 

Upvotes: 1

Views: 59

Answers (0)

Related Questions