gpt4 book ai didi

c++ - 如何检查 C++ 类是否不完整(仅声明)?

转载 作者:行者123 更新时间:2023-12-04 12:31:45 24 4
gpt4 key购买 nike

我想编写一个 C++ 函数来检查它的模板参数类是否不完整,因此只有类声明可用但没有所有类成员的完整定义。

我的函数 incomplete() 与一些演示程序一起看起来如下:

#include <type_traits>
#include <iostream>

template <typename T, typename V = void> constexpr bool is_incomplete = true;
template <typename T> constexpr bool is_incomplete<T, std::enable_if_t<sizeof(T)>> = false;
template <typename T> constexpr bool incomplete() { return is_incomplete<T>; }

struct A;
void print() { std::cout << incomplete<A>(); }
struct A {}; //this line affects GCC

int main()
{
print();
}

它在 Clang 打印 1 中运行良好,但在 GCC 中程序打印 0 尽管 A 类在功能上不完整 打印https://gcc.godbolt.org/z/qWW3hqbEv

这里是GCC错了还是我的程序有问题?

最佳答案

目前尚未确定哪个编译器是正确的。这是CWG Issue 1845 .

The current wording of 13.8.4.1 [temp.point] does not define the point of instantiation of a variable template specialization. Presumably replacing the references to “static data member of a class template” with “variable template” in paragraphs 1 and 8 would be sufficient.

鉴于该问题仍处于起草阶段(并且没有规范性措辞,但它是最新的可用草案),它仍未得到解决。目前尚不清楚变量模板是否可以具有多个实例化点(尽管问题报告者建议的方向很明确)。

对于具有多个实例化点的实体,翻译单元的结尾也是一个。此外,如果有两点不同意模板的定义,那就是 ODR 违规,简单明了。 GCC 似乎提供了两点,因此您可以看到结果。我在这里倾向于同意 GCC。变量模板在很多方面是类模板静态数据成员的简写,而静态数据成员确实有多个实例化点。

无论哪种方式,这都是在冒鼻魔的风险。如果该状态可以在 TU 中更改(甚至可能在整个程序中更改),则实际上不可能可靠地检查类型的完整性。

关于c++ - 如何检查 C++ 类是否不完整(仅声明)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68573739/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com