mercredi 17 août 2016

Wrapping Microsoft's "W" and "A" functions

I'm writing a template function which uses notorious Microsoft's A and W functions. Template argument type is limited to std::string and std::wstring, therefore I use struct wrapper to call required function:

template<typename type>
struct formatMessageT;

template<>
struct formatMessageT<std::string> {
    static inline size_t call(DWORD dwFlags, LPCVOID lpSource, DWORD dwMessageId, DWORD dwLanguageId, LPSTR lpBuffer, DWORD nSize, va_list *Arguments) {
        return FormatMessageA(dwFlags, lpSource, dwMessageId, dwLanguageId, lpBuffer, nSize, Arguments);
    }
};

template<>
struct formatMessageT<std::wstring> {
    static inline size_t call(DWORD dwFlags, LPCVOID lpSource, DWORD dwMessageId, DWORD dwLanguageId, LPWSTR lpBuffer, DWORD nSize, va_list *Arguments) {
        return FormatMessageW(dwFlags, lpSource, dwMessageId, dwLanguageId, lpBuffer, nSize, Arguments);
    }
};

This, however, is a pain in... Is there a better way to achieve this? I tried to use function template, as seen below:

#include <iostream>

char funW(wchar_t) {
    return 'W';
}

char funA(char) {
    return 'A';
}

template<typename returnType, typename function, typename ...Args>
returnType functionCall(function f, Args ...args) {
    return f(args...);
}

int main() {
    bool dummy = true;
    std::cout << functionCall<char>(dummy ? funW : funA, dummy ? L'W' : 'A') << std::endl;

    std::cin.get();

    return 0;
}

Unfortunately this only works when function arguments types match (given that argument itself also matches):

char funW(char) {
    return 'W';
}

char funA(char) {
    return 'A';
}

or

char funW(wchar_t) {
    return 'W';
}

char funA(wchar_t) {
    return 'A';
}

Aucun commentaire:

Enregistrer un commentaire