模板别名上的is_same_template行为奇怪

Strange behaviour of is_same_template on template aliases

本文关键字:template same 别名 is      更新时间:2023-10-16

以下程序...

#include <iostream>
#include <type_traits>
template <typename T>
struct Template{};
template <typename T>
using Alias = Template<T>;
template
    <
        template <typename>
        class T1,
        template <typename>
        class T2
    >
struct is_same_template : std::false_type{};
template
    <
        template <typename>
        class T
    >
struct is_same_template<T, T> : std::true_type{};
int main() {
    std::cout << std::boolalpha;
    std::cout << "Template == Template: " << is_same_template<Template, Template>::value << std::endl;
    std::cout << "Template == Alias: " << is_same_template<Template, Alias>::value << std::endl;
    std::cout << "Alias == Alias: " << is_same_template<Alias, Alias>::value << std::endl;
}

。输出。。。

Template == Template: true
Template == Alias: false
Alias == Alias: true

。使用 G++ 4.8.1、Clang 3.4VC++ 18.00.21005.1 编译。

是这些编译器中的错误还是标准的要求?

这是标准要求的行为,这是完全合乎逻辑的。别名模板不是模板别名(尽管有些人打算这样做)。最初,即使在标准中似乎也存在一些混淆,请参阅 http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1244 。

在当前的标准化表单中,别名模板类似于其非模板化的对应部分:它为类型设置别名。在模板版本中,类型可能相关。

并立即被取代。例如,Alias<T> T本身就是模板参数,它将是依赖类型Template<T> - 从这个意义上说,名称别名模板可能有点混乱,因为它表明会在某个时候实例化别名声明。但实际上别名模式会立即被替换 - 从这个意义上说,模板化版本更像是一个始终存在且不需要实例化的依赖别名声明,而不是别名声明模板。

不过,在这一点上,我们用这些术语的确切含义变得有点哲学化。