加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 在保证副本省略的世界中的构造函数实例化

发布时间:2020-12-16 03:32:28 所属栏目:百科 来源:网络整理
导读:考虑这个例子: template typename Tusing type = typename T::type;template typename Tstruct A{ A(typeT);};Aint f();Aint g() { return f(); } 由于没有嵌套类型typedef,gcc和clang都没有编译这段代码.但是为什么构造函数会被实例化呢? f()是与g()返回
考虑这个例子:
template <typename T>
using type = typename T::type;

template <typename T>
struct A
{
    A(type<T>);
};

A<int> f();
A<int> g() { return f(); }

由于没有嵌套类型typedef,gcc和clang都没有编译这段代码.但是为什么构造函数会被实例化呢? f()是与g()返回相同类型的prvalue,甚至不应该在那里移动.是什么导致我们实例化坏构造函数?

解决方法

构造函数有点像红鲱鱼.如果它是任何其他成员函数,也会发生同样的情况.
template <typename T>
struct A
{
    void foo(type<T>); // Same error
};

这是因为[temp.inst]/2

The implicit instantiation of a class template specialization causes
the implicit instantiation of the declarations,but not of the
definitions,default arguments,or noexcept-specifiers of the class
member functions,[…]

声明被实例化,因此键入< T>必须是良好的形式.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读