【问题标题】:c++ perfect forwarding with universal reference prevents type deduction?具有通用引用的c ++完美转发可防止类型推断?
【发布时间】:2021-05-14 09:57:52
【问题描述】:

我考虑以下 2 个做同样事情的 sn-ps。在第一种情况下,我没有使用通用引用,因此我必须编写函数set 两次。在第二种情况下,使用通用引用我可以编写一次函数,但是该类的用户必须明确指定传递给函数set 的类型。有没有什么技巧可以兼得?

#include <iostream>

struct A {};

template<typename T>
struct B {

    void set(const A& a) {
        a_=a;
    }
    
    void set(A&& a) {
        a_=std::forward<A>(a);
    }

    A a_;
};

int main() {

    B<A> b;
    A a;

    b.set({});
    b.set(a);

    return 0;
}

和

#include <iostream>

struct A {};

template<typename T>
struct B {

    template<typename U>
    void set(U&& a) {
        a_=std::forward<U>(a);
    }
    
    A a_;
};

int main() {

    B<A> b;
    A a;

    b.set(A{}); // here I can't do b.set({}) because the template parameter U would be undefined
    b.set(a);

    return 0;
}

【问题讨论】:

    标签: c++ perfect-forwarding type-deduction forwarding-reference


    【解决方案1】:

    在这种情况下,您可以为U 模板参数添加一个默认值,例如

    template<typename U = T>
    void set(U&& a) {
        a_=std::forward<U>(a);
    }
    

    现在如果它可以推断出类型,例如没有类型的{},那么它将使用T 作为U 的类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-09
      • 1970-01-01
      • 2019-06-22
      • 1970-01-01
      • 2015-04-22
      • 2021-06-17
      • 1970-01-01
      相关资源
      最近更新 更多