Wiesz co, pewnie że się da. Ale ani to ładne ani bezpieczne. Myślę że sensowniej przemyśleć sprawę. Tu masz ideowo zaimplementowane. Nie będę silił się na poprawność. Osobiście jeśli przy takim problemie mam robić reinterpret_cast na poziomie logiki, to najczęściej oznacza nieprzemyślany problem. Ale ok... :
#include <iostream>
#include <cassert>
#include <cstddef>
#include <algorithm>
struct Data {
int a;
int b;
int c;
int d;
};
int main() {
Data table[] = { {1, 2, 3, 4}, {10, 5, 1, 2}, {12, 3, 4, 3} };
std::size_t offsets[] = { offsetof(Data, a), offsetof(Data, b), offsetof(Data, c), offsetof(Data, d) };
char l;
std::cout << "Podaj nazwę pola wg. którego sortować w postaci litery [a-d]: ";
std::cin >> l;
assert(l >= 'a' && l <= 'd');
std::size_t offset = offsets[l - 'a'];
std::sort(std::begin(table), std::end(table), [offset](Data d1, Data d2) {
return static_cast<int>(*(reinterpret_cast<char *>(&d1) + offset))
< static_cast<int>(*(reinterpret_cast<char *>(&d2) + offset));
});
for (auto v: table) {
std::cout << "a = " << v.a << " b = " << v.b << " c = " << v.c
<< " d = " << v.d << '\n';
}
}
PS. Jeśli typy dla pól w strukturze były by różne, także się da ale kod byłby jeszcze bardziej usiany dziwnymi rzutowaniami (i było by przejście przez void * co już samo z siebie w C++ na poziomie logiki powinno powodować uruchomienie alarmu we wszystkich samochodach w promieniu 3 km):)