c++ - 结合完美转发模板和任意值类型模板

标签 c++ templates stl move-semantics sfinae

  1. 我有这个函数模板foo接受任何包含 int 的 STL 容器:

    template <typename ContainerType, std::enable_if_t<std::is_same<typename ContainerType::value_type, int>::value, int> = 0>
    void foo(ContainerType const& list)
    { /* */ }
    
  2. 我有这个函数模板bar这需要 std::vector<int>并将其转换为完美转发(或引用转发,无论您如何调用它):

    template <typename ContainerType, std::enable_if_t<std::is_same<std::decay_t<ContainerType>, std::vector<int>>::value, int> = 0>
    void bar(ContainerType&& list)
    { /* */ }
    

int main(void)
{
    std::initializer_list<int> list{1, 2, 3};
    std::vector<int> vec{1, 2, 3};

    foo(list);  // OK
    foo(vec);  // OK
    foo(std::vector<int>{4, 5, 6});  // OK, but copy-semantics

    bar(vec);  // OK
    bar(std::vector<int>{4,5,6});  // OK
    bar(list);  // ERROR
}

我想把这两个合二为一,得到一个接受STL容器的模板函数value_type int并为完美转发做好准备。我怎样才能做到这一点?

最佳答案

就结合你的条件吧。我们想要一个接受转发引用的函数:

template <class C, class = std::enable_if_t<???> >
void quux(C&& container);

而你想要 value_type标的containerint .让我们将其放入其自身的可读性特征中:

template <class C>
using is_int_container = std::is_same<typename C::value_type, int>;

现在,不能只做 is_int_container<C>因为C目前可以引用或引用const .但我们可以用 std::decay 来解决这个问题:

template <class C, class = std::enable_if_t<is_int_container<std::decay_t<C>>::value >>
void quux(C&& container);

关于c++ - 结合完美转发模板和任意值类型模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35924117/

相关文章:

c++ - 为什么我不能用括号初始化从另一个结构派生的结构?

python - 将 Python.h 嵌入/包含到 C++ 中 [完整指南] (Python 3.9) (Windows) (Qt 5.15)

c++ - 交换两个 boost::adjacency_list 图,类似于 std::swap

c++ 在已知位置插入 vector

c++ - 非静态成员数组初始化的任何解决方法?

azure - 如何安排部署ARM模板?

c++ - 如何创建具有任意数量(编译时确定)容器的内存池?

c++ - 为什么将 std::sort 与自定义比较器一起使用无法编译?

c++ - std::list 是否保证项目永远不会移动到不同的内存位置?

c++ - 出于一般原因抛出异常c++