templates - C++ function switch on value -


i have templated function

template <typename s, typename t> string dostuff(const s& s, const t& t, const string& format) {     ... } 

but format changes function's behaviour (imagine values "csv", "json", etc.). make bit more sense have separate functions.

i feel i'm missing obvious, should possible sort of specialisation. otherwise, have add dispatch function, work feels i've missed obvious.

template <typename s, typename t> string dostuff(const s& s, const t& t, const string& format) {     if (format == "csv")         return dostuffcsv(s, t);     if (format == "json")         return dostuffjson(s, t);     // ... }  template <typename s, typename t> string dostuffcsv(const s& s, const t& t) { ... }  template <typename s, typename t> string dostuffjson(const s& s, const t& t) { ... } 

conceptually, want (which of course doesn't work)

template <typename s, typename t, string("csv")> string dostuff(const s& s, const t& t) { ... }  template <typename s, typename t, string("json")> string dostuff(const s& s, const t& t) { ... } 

as @bolov , @nathan oliver write, can enum.

to branch @ compile time, i'd add std::integral_constant:

#include <type_traits>                                                                                                                                                                                     enum class type {        txt = 1,     cst = 2, };    using txt_specifier = std::integral_constant<type, type::txt>; using csv_specifier = std::integral_constant<type, type::csv>; 

the latter 2 types, , can overload on them @ compile time (and using numeric values, fancy metaprogramming things if needed further).


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -