【问题标题】:why is this short snippet of template code valid?为什么这个简短的模板代码片段有效?
【发布时间】:2017-05-18 09:45:08
【问题描述】:

根据标题,当has_type_struct<no_type>肯定是无效类型时,我不明白以下代码如何编译。

template<typename T>
using my_int = int;

struct no_type {};

template<typename T>
struct has_type_struct { using type = typename T::type; };

template<typename T>
using has_type_using = typename T::type;

int main() {
   my_int<has_type_struct<no_type>> a; // why does this compile?
   //my_int<has_type_using<no_type>>(); // this rightfully does not compile
   return 0;
}

【问题讨论】:

    标签: c++ templates metaprogramming


    【解决方案1】:

    程序有效,因为has_type_struct&lt;no_type&gt; 没有被实例化。

    [temp.inst]/1:

    除非已显式实例化或显式特化类模板特化,否则当在需要完全定义的对象类型的上下文中引用特化或类类型的完整性影响语义时,会隐式实例化类模板特化的程序。

    my_int&lt;has_type_struct&lt;no_type&gt;&gt; 的使用并不要求 has_type_struct&lt;no_type&gt; 是完整的,因此后者不会被实例化,也不会检查其定义中依赖名称的有效性。

    【讨论】:

    • 我认为在这种情况下从未检查过模板参数的有效性是非常令人惊讶的,但看起来这是标准语言的 sn-p 的直接结果。
    • 附注w.r.t.标准,有人可能会争辩说,在这种情况下,“类类型的完整性”确实会影响“程序的语义”,但是哦,好吧
    • 类型的完整性意味着特定的东西,请参阅here。在您的情况下,完整性不会影响语义。再举一个例子,我们可以前向声明一个类模板以用作模板参数:template &lt;typename&gt; class fwd; my_int&lt;fwd&lt;short&gt;&gt; b; 如果我们为fwd 提供定义,b 的类型不会改变。
    猜你喜欢
    • 2012-11-06
    • 2014-02-02
    • 2013-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多