c++ - 完美转发到基类

标签 c++ c++11

#include <utility>
#include <vector>
#include <cstdint>

template <typename T>
struct Base
{
protected:
    Base(T&& data):
        data(std::forward(data)){
    }
    virtual ~Base(){};

public:

    T getData() const {return data;}

    void setData(T&& data) {
       this->data = std::forward(data);
    }
private:
    T data;
};


struct DerivedA: public Base<int>
{
public:
    DerivedA(int data):
        Base(std::move(data)){//Should I use std::forward instead of std::move here?
    }
};

struct DerivedB: public Base<const std::vector<uint16_t> >
{
public:
    DerivedB(const std::vector<uint16_t>& data):
        Base(std::move(data)){
    }
};

我的要求是在创建上面的派生类时有 0 个对象拷贝。 但无论我如何编写上面的代码,我都会遇到编译器错误,这些是最新的:

bin/Base.h: In instantiation of ‘Base<T>::Base(int, int, int, T&&) [with T = int]’:
bin/Base.h:33:82:   required from here
bin/Base.h:12:96: error: no matching function for call to ‘forward(int&)’
/usr/include/c++/4.7/bits/move.h:77:5: note: template<class _Tp> constexpr _Tp&& std::forward(typename std::remove_reference<_Tp>::type&)
/usr/include/c++/4.7/bits/move.h:77:5: note:   template argument deduction/substitution

我在这里做错了什么?

此外,当 dataintstd::forward< 时,我是否应该执行 std::move(data)/?

最佳答案

如果你想完美地转发一个参数,你要么需要提供相应的三个重载,要么使参数成为模板参数。无论哪种情况,当您想使用 std::forward() 时您需要指定第一个模板参数,因为它不是推导出来的。最有可能的是,你会使用这样的东西:

template <typename T>
class Base {
public:
    template <typename A>
    Base(A&& data): data(std::forward<A>(data)) {}
};

尝试 std::move(data)什么时候datastd::vector<uint16_t> const&不会移动 vector ,也不会使对象看起来像非 const右值:如果你想让 vector 可移动,你需要将它作为非 const 传递引用、右值或值。您可能还想推断 std::vector<uint16_t>&& 上的类型或重载和 std::vector<uint16_t>& .对于这两个重载,使用 std::move()做的伎俩。如果您推断类型,您将使用 std::forward<A>(data)再次。如果推导的类型看起来很吓人,您可以使用 std::enable_if<...> 对其进行约束。使用这样的东西:

template <typename A>
DerivedB(A&& arg,
         typename std::enable_if<std::is_same<typename std::decay<A>::value,
                                              std::vector<uint16_t>>::value>::type* = 0):
    Base(std::forward<A>(arg)) {
}

关于c++ - 完美转发到基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27221886/

相关文章:

c++ - 用于输出的 visual studio code C++ 终端

c++ - XSD : How to set attributes values in children element type?

c++ - 如何检查两个元组的所有成员是否不同?

c++ 整数的幂,模板元编程

c++ - C++ [Xcode] 中可变数量的参数

c++ - DirectX 11 E_INVALIDARG 在设备创建期间

c++ - 如何让 GNU __attribute__((constructor)) 在库中工作?

c++ - 这是交换(多线程)的异常安全实现吗?

c++ - 支持 c++11 的 Makefile

c++ - 为什么 std::pair 对 const 引用和转发引用参数有两个不同的构造函数?