对于您想要的功能,...
- 在编译时获取长度,
- 可以包含在.H没有连接怨天尤人,
- 中的.o无多拷贝,在联动输出,
...你可以使用模板不变成语,像
template< class Dummy >
struct Foo_
{
static char const s[];
};
template< class Dummy >
char const Foo_<Dummy>::s[] = "Blah blah";
typedef Foo_<void> Foo; // Now you can refer to Foo:s
#include <iostream>
using namespace std;
int main()
{
cout << sizeof(Foo::s) << " bytes: \"" << Foo::s << "\"\n";
}
您可以将生成包装在宏中。
然而,据我所知,唯一的实用工具是支持char/wchar_t-agnostic代码,并且为此痛苦可能会大于增益。
编辑:
MSVC版本7.1向上穿过10.0正确不接受sizeof
。以下是一个解决方法,可以很好地编译g ++ 4.4.1,Comeau Online 4.3.10.1,MSVC 7.1和MSVC 10.0。
#include <stddef.h>
typedef ptrdiff_t Size;
// Substitute a more general countOf
template< Size n >
struct SizedBuf { char sizer[n]; };
template< class Type, Size n >
SizedBuf<n> countOf_(Type (&)[n]) { return n; }
#define COUNT_OF(array) sizeof(countOf_(array).sizer)
#define DEF_STRING(name, value) \
template<class> \
struct name##_constant_ \
{ \
static char const str[]; \
static Size const length = COUNT_OF(value) - 1; \
}; \
\
template< class Type > \
char const name##_constant_<Type>::str[] = value; \
\
template< class Type > \
Size const name##_constant_<Type>::length; \
\
typedef name##_constant_<void> name;
DEF_STRING(a, "Argh, MSVC!")
DEF_STRING(b, "Blah blah")
DEF_STRING(c, "Currently there's no 'inline' for data in C++.")
#include <iostream>
template< char const* s >
void foo() { std::cout << "foo() says: " << s << std::endl; }
int main()
{
using namespace std;
int const x[a::length] = {}; // Showing off compile time constant.
foo<a::str>(); // Showing off external linkage.
cout << a::length << " characters: \"" << a::str << "\"." << endl;
}
干杯&心连心,
恩,功能不矛盾。呃,现在解释一下,我将不得不添加一个答案。就这样吧。干杯, – 2010-10-21 21:54:45
#define可以在sizeof – pm100 2010-10-21 22:41:09
@ pm100下正常工作:它的行为与静态类似,因为它给你(1)和(2)的代价是在每个编译单元中生成一个副本(尽管它保证不会是除非实际使用,否则生成)。 – 2010-10-21 23:01:18