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

pts*_*pts 1 c++ containers templates

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

template<typename Input, typename Output>
void Process(const Input &in, Output *out) {
  ...
}
Run Code Online (Sandbox Code Playgroud)
  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);应该是编译错误.`

Die*_*ühl 9

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

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");
Run Code Online (Sandbox Code Playgroud)

如果您希望您的类型可以转换,您可以使用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");
Run Code Online (Sandbox Code Playgroud)

  • 从好的方面来说,`enable_if`适用于C + 98 :-) (2认同)