Chcę wydedukować typy parametrów funkcji z ciągu znaków. Podobne do tego, co robi printf.Typ zapytania z ciągu literowego
Obecnie należy wykonać następujące czynności:
#include <utility>
// calculate the length of a literal string
constexpr int length(const char* str)
{
return *str ? 1 + length(str + 1) : 0;
}
struct Ignore {
};
template <char C1, char C2>
struct Type {
typedef Ignore type;
};
// %d -> int
template <>
struct Type<'%','d'> {
typedef int type;
};
// %f -> float
template <>
struct Type<'%','f'> {
typedef float type;
};
// Get type from string
template <const char * const * const STR, int POS, int N = length(STR[POS])>
struct GetType {
typedef Ignore type;
};
template <const char * const * const STR, int POS>
struct GetType<STR, POS, 2> {
typedef typename Type<STR[POS][0],STR[POS][1]>::type type;
};
// My dummy class
template <typename... Targs>
struct Foo
{
void Send(Targs...) const {}
};
// Deduce type for each literal string array
template <const char * const * STRS, std::size_t N, std::size_t... index>
constexpr auto parseIt(std::index_sequence<index...>) {
return Foo<typename GetType<STRS, index>::type...>();
}
template <const char * const * STRS, std::size_t N>
constexpr auto makeFoo(const char * const (&a)[N]) {
return parseIt<STRS, 2>(std::make_index_sequence<N>{});
}
Problem polega na tym, muszę napisać Ignoruj () na moje wezwanie funkcji ...
constexpr const char *message[] = {"%d", " hello ", "%f", "good"};
constexpr auto foo = makeFoo<message>(message);
int main()
{
foo .Send(10, Ignore(), 20.0f, Ignore());
return 0;
}
co chcę to coś w stylu (kontrola tylko w czasie kompilacji):
MyFoo foo("%d Hello World %f %s");
foo.Send(10, 20.f, "Hello");
Musisz sprawdzić w środowisku wykonawczym, czy typ parametru odpowiada oczekiwanemu typowi zgodnie z zawartością łańcucha – Garf365
Dziękuję, ale chcę mieć kontrolę czasu kompilacji. (Dodano do pytania.) – Viatorus
Musisz sparsować stały ciąg znaków za pomocą meta-programowania C++, aby pobrać argumenty szablonu dla twojej instancji MyFoo, aby zdefiniować parametry elementu Wyślij. Wymagałoby to jednak sprawdzenia bajtu po bajcie, wielu odmian i ograniczeń. Wdrożenie wersji środowiska wykonawczego byłoby lepszym wyborem. – Youka