且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是由C ++标准定义的空结构吗?

更新时间:2023-11-29 15:47:22

一个在c ++标准库中的东西。如评论中所述,您仍然可以找到 提升:: blank 在Boost,这可能是最类似于你正在寻找的类。如果这样的类存在于标准库中,我不认为会有那么多第三方库定义自己的 struct empty {}

There is no such a thing in the c++ standard library. As mentioned in the comments, you can still find boost::blank in Boost which is probably what resembles the most to the class you are looking for. If such a class existed in the standard library, I don't think there would be so many third-party libraries defining their own struct empty {}.

如果你想要的只是一个没有数据成员和最小可能大小的类 - 不能小于1 - (并且可能受益于空基本优化),你仍然可以使用 std :: tuple<> 。它实际上用于在libstdc ++中的某些类的实现中的确切目的(空基本优化)。

If what you want is just a class with no data members and the smallest possible size - cannot be smaller than 1 - (and possibly benefit from the empty base optimization), you can still use std::tuple<>. It is actually used for that exact purpose (empty base optimization) in the implementation of some classes in the libstdc++.

如果你想确保 std :: tuple<> 真的是一个空类:

If you want to make sure std::tuple<> really is an empty class:

#include <iostream>
#include <tuple>
#include <type_traits>

int main()
{
    // prints 1
    std::cout << std::is_empty< std::tuple<> >::value;
}