我有一个 C++ 模板函数:
template<typename Input, typename Output>
void Process(const Input &in, Output *out) {
...
}
如果使用不同类型的容器调用它,我如何使其成为带有友好错误消息的编译错误?例如,调用
set<int> sout; Process(vector<int>(), &sout);
应该可以,但是vector<unsigned> vout; Process(vector<int>(), &vout);
应该是编译错误。如果使用不可相互转换的容器调用它,我如何使其成为带有友好错误消息的编译错误?例如,上面的调用应该有效,但是
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");
关于c++ - 将 C++ 模板参数限制为相同值类型的容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20859950/