如何区分空结构和一个字符?
How to distinguish empty struct from one char?
我正在尝试实现自己的仿函数,但遇到了空的捕获 lambda。如何区分空结构和一个字符?编译时是否有 "real" 大小?我只想忽略空的 lambda 以防止无用的分配。
struct EmptyStruct {};
struct CharStruct { char c; };
int main()
{
char buffer1[sizeof(EmptyStruct)]; // size 1 byte
char buffer2[sizeof(CharStruct)]; // size 1 byte
}
你cannot do that with sizeof()
, use std::is_empty
,像这样:
#include <iostream>
#include <type_traits>
struct EmptyStruct {};
struct CharStruct { char c; };
int main(void)
{
std::cout << std::boolalpha;
std::cout << "EmptyStruct " << std::is_empty<EmptyStruct>::value << '\n';
std::cout << "CharStruct " << std::is_empty<CharStruct>::value << '\n';
return 0;
}
输出:
EmptyStruct true
CharStruct false
正如@RichardCritten 评论的那样。
我正在尝试实现自己的仿函数,但遇到了空的捕获 lambda。如何区分空结构和一个字符?编译时是否有 "real" 大小?我只想忽略空的 lambda 以防止无用的分配。
struct EmptyStruct {};
struct CharStruct { char c; };
int main()
{
char buffer1[sizeof(EmptyStruct)]; // size 1 byte
char buffer2[sizeof(CharStruct)]; // size 1 byte
}
你cannot do that with sizeof()
, use std::is_empty
,像这样:
#include <iostream>
#include <type_traits>
struct EmptyStruct {};
struct CharStruct { char c; };
int main(void)
{
std::cout << std::boolalpha;
std::cout << "EmptyStruct " << std::is_empty<EmptyStruct>::value << '\n';
std::cout << "CharStruct " << std::is_empty<CharStruct>::value << '\n';
return 0;
}
输出:
EmptyStruct true
CharStruct false
正如@RichardCritten 评论的那样。