解释后面C ++测验通过Olve Maudal(别名模板) [英] Explanation behind C++ Quiz by Olve Maudal (alias template)
问题描述
以下代码来自 http://www.pvv.org/~oma/PubQuiz_ACCU_Apr2014.pdf(#6,第34页上的解决方案)。目标是猜测以下内容的输出。
The following code is from http://www.pvv.org/~oma/PubQuiz_ACCU_Apr2014.pdf (#6, solution on page 34). The goal was to guess the output for the following.
#include <iostream>
template <template <typename> class>
struct X {
X() { std::cout << "1"; }
};
template<typename >
struct Y {};
template<typename T>
using Z = Y<T>;
template<>
struct X<Y> {
X() { std::cout << "2"; }
};
int main() {
X<Y> x1;
X<Z> x2;
}
答案可以在第34页找到。具有别名模板的情况下,为什么为 X
选择主模板而不是完全专用。
The answer can be found on page 34. I don’t understand the second case with the alias template, why the primary template is chosen for X<Z>
instead of the fully specialized.
正确的答案应该是21。 My MinGW(gcc 5.1)打印22, http://ideone.com (使用gcc 4.9.2)也打印22。来自MacOS X上的朋友的昵称打印21。所以我猜这是gcc中的一个错误。
The correct answer should be "21" as written in the presentaton. My MinGW (gcc 5.1) prints "22" and http://ideone.com (which uses gcc 4.9.2) also prints "22". Clang from a friend on MacOS X prints "21". So I guess this is a bug in gcc.
任何人都可以解释为什么为 X< Z& code>以及标准gcc中的哪个段落可能无法实现或尚未实现?
Can anyone explain to me why "1" is printed for the X<Z>
and what paragraph from the standard gcc might failed to implement or not yet implemented?
推荐答案
14.5.7别名模板
1 其中声明是别名声明(第7条)的模板声明声明 别名模板。别名模板是一系列类型的名称。别名模板的名称是模板名称。
14.5.7 Alias templates
1 A template-declaration in which the declaration is an alias-declaration (Clause 7) declares the identifier to be a alias template. An alias template is a name for a family of types. The name of the alias template is a template-name.
上面的意思是 Y
和 Z
是不同的 template-name ,因此它们是不同的模板。可能会让你/编译器困惑的是, Y
和 Z
。
The above means that Y
and Z
are different template-names, so they are different templates. What might confuse you/the compiler is that Y<T>
and Z<T>
will always yield an identical type.
请考虑:
#include <type_traits>
template <typename>
struct W {};
template <template <typename> class>
struct X {};
template<typename>
struct Y {};
template<typename T>
using Z = Y<T>;
int main()
{
static_assert( std::is_same< Y<int>, Z<int> >::value, "Oops" );
static_assert( std::is_same< W<Y<int>>, W<Z<int>> >::value, "Oops" );
static_assert( ! std::is_same< X<Y>, X<Z> >::value, "Oops" );
}
上述工作适用于Clang,
The above works for Clang, but not for GCC.
编辑:正如@TC所指出的有一个有效的 CWG问题1286 ,其中建议该Clang正在做什么标准目前说,但不是想要的。
As pointed out by @T.C. there is an active CWG issue 1286 which suggests that Clang is doing what the standard currently says, but not what was intended.
这篇关于解释后面C ++测验通过Olve Maudal(别名模板)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!