c++ - Differentiating additive types? -
my first steps in generic programming consists of writing simple function accumulates sum of vector passed argument. catch function should work types values makes sense sum.
the code simple:
template <typename t> t accumulate_sum (const std::vector<t>& v) { // check type , decide whether sum or return nothing t sum = v[0]; (size_t = 1; < v.size(); ++i) sum += v[i]; return sum; }
the question how differentiate additive types?
a template function imposes implicit interface on template parameters. if there no operator+=
type t
, compiler error.
#include <cstddef> #include <vector> using namespace std; template <typename t> t accumulate_sum (const std::vector<t>& v) { // check type , decide whether sum or return nothing t sum = v[0]; (size_t = 1; < v.size(); ++i) sum += v[i]; return sum; } struct test {}; // not additive int main() { std::vector<test> v { test{}, test{} }; accumulate_sum(v); }
this give following error message (live example)
main.cpp:10:47: error: no viable overloaded '+=' (size_t = 1; < v.size(); ++i) sum += v[i]; ~~~ ^ ~~~~ main.cpp:19:5: note: in instantiation of function template specialization 'accumulate_sum<test>' requested here accumulate_sum(v); ^ 1 error generated.
with concepts technical specification, can add syntactic constraits , better error messages. static_assert
well.
#include <experimental/type_traits> #include <utility> template<class t> using add_inc_t = decltype(std::declval<t&>() += std::declval<t>()); template<class t> constexpr auto is_additive_v = std::experimental::is_detected_v<add_inc_t, t>; template <typename t> t accumulate_sum (const std::vector<t>& v) { static_assert(is_additive_v<t>, "the type t needs additive providing operator+"); // before }
live example using gcc 6.0 svn trunk (not yet released).
Comments
Post a Comment