[英]Wrapping Microsoft's “W” and “A” functions
我正在編寫一個使用臭名昭著的Microsoft A
和W
函數的模板函數。 模板參數類型僅限於std::string
和std::wstring
,因此我使用struct
wrapper調用所需的函數:
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);
}
};
但是,這令人感到痛苦……是否有更好的方法來實現這一目標? 我嘗試使用功能模板,如下所示:
#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;
}
不幸的是,這僅在函數參數類型匹配時起作用(假設參數本身也匹配):
char funW(char) {
return 'W';
}
char funA(char) {
return 'A';
}
要么
char funW(wchar_t) {
return 'W';
}
char funA(wchar_t) {
return 'A';
}
一個刪除了答案的人發布了不適用於Microsoft編譯器的解決方案,但是在修改了代碼之后,我設法對其進行了修改並使其起作用。 非常感謝您(WF或類似的人)!
#include <iostream>
#include <utility>
template <bool, class T1, class T2, T1, T2>
struct nontype_conditional;
template <class T1, class T2, T1 Foo1, T2 Foo2>
struct nontype_conditional<true, T1, T2, Foo1, Foo2> {
template<typename ...Args>
static auto run(Args&&... args) {
return Foo1(std::forward<decltype(args) && >(args)...);
}
};
template <class T1, class T2, T1 Foo1, T2 Foo2>
struct nontype_conditional<false, T1, T2, Foo1, Foo2> {
template<typename ...Args>
static auto run(Args&&... args) {
return Foo2(std::forward<decltype(args) && >(args)...);
}
};
char funW(char) {
return 'W';
}
char funA(wchar_t) {
return 'A';
}
constexpr bool value = true;
int main() {
std::cout << nontype_conditional<value, decltype(funW)&, decltype(funA)&, funW, funA>::run(value ? 'a' : L'a') << std::endl;
std::cin.get();
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.