简体   繁体   English

我可以使用C ++模板生成函数的Unicode / ANSI变体,而不使用预处理器吗?

[英]Can I use C++ templates to generate Unicode/ANSI variants of a function, rather than using the preprocessor?

We've got a bunch of legacy code that doesn't support Unicode, so a transitional pattern we use in our code is to move the function to a .inl file, change char to CHAR_TYPE , and then wrap it up like this: 我们有一堆不支持Unicode的旧代码,因此我们在代码中使用的过渡模式是将函数移至.inl文件,将char更改为CHAR_TYPE ,然后将其包装如下:

#define CHAR_TYPE wchar_t
#define STRING_TYPE std::wstring
#define MyFunctionName MyFunctionNameW
#include "MyFunction.inl"

#undef CHAR_TYPE
#define CHAR_TYPE char
#undef STRING_TYPE
#define STRING_TYPE std::string
#undef MyFunctionName
#define MyFunctionName MyFunctionNameA
#include "MyFunction.inl"

...where MyFunction.inl then defines MyFunctionName , using the macros to generate both an 'A' version and a 'W' version. ...然后MyFunction.inl定义MyFunctionName ,使用宏生成“ A”版本和“ W”版本。

This is icky, but it's unfortunately necessary until we get all of our code converted to support Unicode. 这很麻烦,但是很遗憾,在我们将所有代码转换为支持Unicode之前,这是必需的。

Is there an alternative way I could do this with templates? 有没有其他方法可以使用模板执行此操作? I'm thinking that something like the following would be nice: 我认为类似以下的内容会很好:

typedef MyFunctionName<wchar_t, std::wstring> MyFunctionNameW
typedef MyFunctionName<char, std::string> MyFunctionNameA

Is this possible? 这可能吗?

Update: I misread the question, thinking you already had A and W functions written which you wanted to call through the same name. 更新:我误解了问题,以为您已经编写了要使用相同名称调用的A和W函数。 What you have is indeed a situation for which templates are designed, but I won't repeat the correct answer. 您所拥有的确实是为模板设计的一种情况,但是我不会重复正确的答案。

Simple overloading works, no need for templates or additional complexity. 简单的重载即可工作,无需模板或其他复杂性。 The Win32 API uses macros because C doesn't have overloading. Win32 API使用宏,因为C没有重载。

inline
void MyFunctionName(std::wstring const& value) { MyFunctionNameW(value); }
inline
void MyFunctionName(std::string const& value) { MyFUnctionNameA(value); }

Roger Pate is entire correct about the interface. Roger Pate对界面完全正确。 You shouldn't bother with A and W suffixes. 您不必理会A和W后缀。 However, this still leaves the problem of implementation. 但是,这仍然存在实施问题。 As you supected, templates are the correct solution. 如您所料,模板是正确的解决方案。 And since you don't need the different names, you can leave out the typedefs. 而且由于不需要其他名称,因此可以省略typedef。 You would just have 你只会有

template <typename TSTRING> void MyFunctionName (TSTRING const&);

是的,这是可能的,这基本上就是std :: string和std :: wstring所做的,因为它们实际上是std::basic_string<charT,traits,alloc> typedef。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM