问题描述
我写了这个 C++11 trait 模板来检查一个类型是否完整:
I wrote this C++11 trait template to check whether a type is complete:
template <typename...>
using void_t = void;
template <typename T, typename = void>
struct is_complete : std::false_type
{};
template <typename T>
struct is_complete<T, void_t<decltype(sizeof(T))>> : std::true_type
{};
并像这样测试:
struct Complete {};
int main()
{
std::cout << is_complete<Complete>::value
<< is_complete<class Incomplete>::value
<< '
';
}
我希望测试程序打印10
,这就是我用clang 3.4 编译它时得到的输出.但是,当使用 gcc 4.9 编译时,它会打印 11
—— 错误地将 class Incomplete
识别为完整.
I expected the test program to print 10
, and that is the output I get when I compile it with clang 3.4. However, when compiled with gcc 4.9, it prints 11
instead -- mistakenly identifying class Incomplete
as complete.
我不确定我的代码是否正确,但在我看来,即使它是错误的,它在两个编译器上的行为也应该相同.
I don't know for sure if my code is correct, but it seems to me that even if it's wrong, it should behave the same on both compilers.
问题 1:我的代码正确吗?
问题 2:我是否在其中一个编译器中发现了错误?
Question 1: Is my code correct?
Question 2: Have I found a bug in one of the compilers?
我不是要求替换我的代码.我在问 gcc 或 clang 中是否存在错误,以及这个特定的构造是否正确.
I'm not asking for a replacement for my code. I'm asking whether there is a bug in gcc or clang, and whether or not this particular construct is correct.
推荐答案
问题似乎出在 void_t
的定义上.定义为
The problem appears to be with the definition of void_t
. Defining it as
template<typename... Ts>
struct make_void { typedef void type;};
template<typename... Ts>
using void_t = typename make_void<Ts...>::type;
而是在两个编译器上产生正确的结果(10
)(Demo).
instead yields the correct result (10
) on both compilers (Demo).
我相信这与 N3911,论文提出了 void_t
和 CWG 问题 1558.本质上,该标准不清楚别名模板特化中未使用的参数是否会导致替换失败或被简单地忽略.委员会 2014 年 11 月会议通过的 CWG 问题决议阐明了问题中 void_t
的较短定义应该有效,并且 GCC 5.0 实施了该决议.
I believe this is the same issue noted in section 2.3 of N3911, the paper proposing void_t
, and CWG issue 1558. Essentially, the standard was unclear whether unused arguments in alias template specializations could result in substitution failure or are simply ignored. The resolution of the CWG issue, adopted at the Committee's November 2014 meeting, clarifies that the shorter definition of void_t
in the question should work, and GCC 5.0 implements the resolution.
这篇关于我对 is_complete 类型特征的实现是否暴露了编译器错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!