【问题标题】:c++ type alias not working when testing specializationc++ 类型别名在测试专业化时不起作用
【发布时间】:2018-11-25 10:57:39
【问题描述】:

使用C++,尝试实现:is_specialization_of

template<typename T, template<typename...> class Template>
struct is_specialization_of : std::false_type {};

template<template<typename...> class Template, typename... Tn>
struct is_specialization_of<Template<Tn...>, Template> : std::true_type {};

template<typename... Tn>
struct tstruct {};

template<typename... Tn>
using ustruct = tstruct<Tn...>;

int main( int argc, char **argv )
{
    printf( "test u<int> against u, return %s\n", is_specialization_of<ustruct<int>, ustruct>::value ? "true" : "false" );
    printf( "test u<int> against t, return %s\n", is_specialization_of<ustruct<int>, tstruct>::value ? "true" : "false" );
    printf( "test t<int> against u return %s\n", is_specialization_of<tstruct<int>, ustruct>::value ? "true" : "false" );
    printf( "test t<int> against t, return %s\n", is_specialization_of<tstruct<int>, tstruct>::value ? "true" : "false" );
    getchar();
    return 0;
}

返回:

test u<int> against u, return false
test u<int> against t, return true
test t<int> against u return false
test t<int> against t, return true

看起来类型别名与原始类型不完全相同

我正在使用 Visual Studio Community 2017

Microsoft (R) C/C++ 优化编译器版本 19.15.26732.1 for x64

但是,当尝试使用 gcc 编译相同的代码时,它会返回:

test u<int> against u, return true
test u<int> against t, return true
test t<int> against u return true
test t<int> against t, return true

有什么办法可以解决吗?

【问题讨论】:

    标签: c++ templates specialization type-alias


    【解决方案1】:

    看起来类型别名与原始类型不完全相同,还是我遗漏了什么?

    别名特化正是它所代表的类型。但是别名 tempalte 是一个完全不同的模板。您的输出原因由 [temp.alias] 指定

    1 一个模板声明,其中的声明是 alias-declaration 将标识符声明为别名模板。一个 别名模板是一系列类型的名称。别名的名称 template 是一个模板名称。

    2 当模板 ID 指代别名的特化时 模板,就相当于得到的关联类型 用它的模板参数替换模板参数 别名模板的 type-id。

    如果我们考虑以上两段来检查您的测试用例,我们会看到:

    1. "test u&lt;int&gt; against u" - ustruct&lt;int&gt; 相当于直接指定tstruct&lt;int&gt;。而tstruct&lt;int&gt; 不是ustruct 的特化。该特征需要评估为假。

    2. test u&lt;int&gt;t - 这里 ustruct&lt;int&gt; 再次等同于直接指定 tstruct&lt;int&gt;。而tstruct&lt;int&gt;tstruct 的特化。该特征应报告为 true。

    3. “测试 t&lt;int&gt;u - tstruct&lt;int&gt; 不是 ustruct 的特化,就像我们之前观察到的那样。该特征应该报告错误。

    4. “测试 t&lt;int&gt;t - 应报告为真。

    在 MSVC 中运行时,您的所有测试都符合 C++ 标准的要求。 GCC 在这里不符合,这是一个编译器错误。

    【讨论】:

    • 感谢您的快速回复。所以如果我们遵循标准,预期的行为应该是:"u 等价于 t" BUT "u is NOT 等价于 t " or "u 和 t 如果不是完整类型就不能比较"
    • @drvkize - ustructtstruct 不是类型,它们是模板。您可以比较它们,它们在符合标准的编译器中不应该相同。比如 Clang coliru.stacked-crooked.com/a/03321a93d172a609 .
    猜你喜欢
    • 1970-01-01
    • 2014-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    相关资源
    最近更新 更多