Reputation: 87361
I have a C++ template function:
template<typename Input, typename Output>
void Process(const Input &in, Output *out) {
...
}
How can I make it a compile error with a friendly error message if it's called with containers of different types? For example, the call set<int> sout; Process(vector<int>(), &sout);
should work, but vector<unsigned> vout; Process(vector<int>(), &vout);
should be a compile error.
How can I make it a compile error with a friendly error message if it's called with containers which are not mutually convertible? For example, the calls above should work, but struct A {}; struct B {}; vector<B> vbout; Process(vector<A>(), &vbout);
should be a compile error. `
Upvotes: 2
Views: 409
Reputation: 153995
You can just static_assert()
that the value_type
s of the two type are the same:
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");
If you want your types to be convertible, you'd use std::is_convertible
instead:
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");
Upvotes: 10