问题描述
是否可以使用宏魔法或TMP在编译时将长度插入到字符串中?
Is it possible using macro magic or TMP to insert the length into a string at compile time?
例如:
const wchar_t* myString = L"Hello";
我希望缓冲区实际包含[length] [string constant]。
I would want the buffer to actually contain "[length] [string constant]".
我使用MSVC 2010缺少constexpr。我想,必须有一些技巧,使这项工作,它可能做:
I'm using MSVC 2010 which lacks constexpr. I figured there must be some trick to make this work as its possible to do:
const wchar_t* myString = L"\x005Hello";
我的尝试到目前为止:
template<int Size>
wchar_t* toBstr(const wchar_t* str)
{
#pragma pack(push)
#pragma pack(1)
struct BStr
{
int len;
wchar_t data[Size];
};
#pragma pack(pop)
static BStr ret;
ret.len = Size;
// don't want to have to copy here, how else could this work??
//ret.data = str;
return ret.data;
}
const wchar_t* m = toBstr<_countof(L"Hello")>(L"Hello");
这个问题似乎相关:
a href =http://stackoverflow.com/questions/4693819/c-template-string-concatenation> C ++范本字串连结
C++ template string concatenation
但不是concat for两个字符串常量,而是从第二个长度生成的常数:)
But not concat for two string constants, rather a constant generated from the length of the 2nd :)
推荐答案
我使用这个简单的宏:
#define DECLARE_BSTR(Variable, String)\
struct \
{ \
uint32_t uLength; \
OLECHAR szData[sizeof(String)]; \
} \
Variable = {sizeof(String) - sizeof(OLECHAR), String};
示例:
ITaskFolder *pTaskFolder;
DECLARE_BSTR(static bstrTaskFolderName, L"\\");
if (SUCCEEDED(pTaskService->GetFolder(bstrTaskFolderName.szData, &pTaskFolder)))
可以用来代替 BSTR
的变体,即没有 .szData
:
Variant which can be used in place of a BSTR
, i.e. without .szData
:
#define DECLARE_BSTR(Variable, String) \
struct \
{ \
uint32_t uLength; \
OLECHAR szData[sizeof(String)]; \
operator const OLECHAR *() const {return szData;}\
operator OLECHAR *() {return szData;}\
} \
Variable = {sizeof(String) - sizeof(OLECHAR), String};
示例:
ITaskFolder *pTaskFolder;
DECLARE_BSTR(static bstrTaskFolderName, L"\\");
if (SUCCEEDED(pTaskService->GetFolder(bstrTaskFolderName, &pTaskFolder)))
这篇关于C ++在编译时创建BSTR /在编译时将长度插入字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!