将模板参数限制为相同值类型的容器C++

Restrict C++ template arguments to containers of the same value type

本文关键字:类型 C++ 参数      更新时间:2023-10-16

我有一个C++模板函数:

template<typename Input, typename Output>
void Process(const Input &in, Output *out) {
  ...
}
  1. 如果使用不同类型的容器调用它,如何使它成为带有友好错误消息的编译错误?例如,调用set<int> sout; Process(vector<int>(), &sout);应该有效,但vector<unsigned> vout; Process(vector<int>(), &vout);应该是编译错误。

  2. 如果使用不可相互转换的容器调用它,如何使它成为带有友好错误消息的编译错误?例如,上面的调用应该有效,但struct A {}; struct B {}; vector<B> vbout; Process(vector<A>(), &vbout);应该是编译错误。`

你可以static_assert()两种类型的value_type是相同的:

static_assert(std::is_same<typename Input::value_type, typename Output::value_type>::value,
              "the containers passed to Process() need to have the same value_type");

如果希望类型可转换,请改用std::is_convertible

static_assert(std::is_convertible<typename Input::value_type, typename Output::value_type>::value,
              "the value_type of the source container passed to Process() needs to be convertible to the value_type of the target container");