繁体   English   中英

完美地将STL容器转发到模板类

[英]Perfect forwarding an STL container to a template class

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

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值构造函数的唯一方法吗?

更简单的确是使用了几个重载:

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;
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM