【问题标题】:Perfect forwarding an STL container to a template class完美地将 STL 容器转发到模板类
【发布时间】:2019-03-28 10:45:46
【问题描述】:

尝试使用完美转发将序列容器传递给模板化的类。例如:

template<template<typename T, typename Alloc> class TContainer, class TObject> 
class A {
public:
    using ContType = TContainer<TObject, std::allocator<TObject>>;

    //This works for R-value references only
    explicit A(ContType&& container) : internalContainer(std::forward<ContType>(container)) {};

    //This does not work - how might I make it work?
    template <typename C>
    explicit A(C&& input) : internalContainer(std::forward<C>(input)) {}

private:
    ContType internalContainer;
};

我有一个问题,我正在尝试定义一个完美的转发构造函数,并且对如何做到这一点有点迷茫。

我在本网站的其他地方读到您不能将显式类型参数传递给构造函数。这样做的唯一方法是提供 R 值和 L 值构造函数吗?

【问题讨论】:

    标签: c++ templates constructor perfect-forwarding


    【解决方案1】:

    使用多个重载确实更简单:

    template<template<typename T, typename Alloc> class TContainer, class TObject> 
    class A {
    public:
        using ContType = TContainer<TObject, std::allocator<TObject>>;
    
        // for R-value
        explicit A(ContType&& container) : internalContainer(std::move(container)) {}
    
        // for L-value
        explicit A(const ContType& container) : internalContainer(container) {}
    
    private:
        ContType internalContainer;
    };
    

    否则,您可能会使用转发引用并使用 SFINAE 进行保护

    template<template<typename T, typename Alloc> class TContainer, class TObject> 
    class A {
    public:
        using ContType = TContainer<TObject, std::allocator<TObject>>;
    
        template <typename T,
                  std::enable_if_t<
                      !std::is_same<A, std::decay_t<T>::value // Protect copy constructor
                      && std::is_constructible<ContType, T&&>::value>, int> = 0>
        explicit A(T&& container) : internalContainer(std::forward<T>(container)) {}
    
    private:
        ContType internalContainer;
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-22
      • 1970-01-01
      • 1970-01-01
      • 2012-01-06
      • 2013-11-17
      • 1970-01-01
      • 2011-09-23
      • 1970-01-01
      相关资源
      最近更新 更多