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

问题描述 投票:1回答:1

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

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个回答
3
投票

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

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;
};
© www.soinside.com 2019 - 2024. All rights reserved.