Retourner au contenu associé (dépêche : C++17 branche à la compilation (`if constexpr`))
Posté par jcelerier le 06 décembre 2016 à 00:13. En réponse à la dépêche C++17 branche à la compilation (`if constexpr`). Évalué à 1. Dernière modification le 06 décembre 2016 à 00:14.
En attendant, on peut tricher un peu en faisant ça :
#include <boost/unordered_map.hpp> #include <variant> struct js_object; using js_value_t = std::variant<int, std::string, bool, js_object>; struct js_object { template<int N> constexpr void set(const char (&s)[N], const js_value_t& value) { if ( str_equal(s, "foo") ) { m_foo = std::get<int>(value); } else if ( str_equal(s, "the_bar") ) { m_bar = std::get<int>(value); } else { m_other[s] = value; } } template<int N> constexpr js_value_t get(const char (&s)[N]) const { if ( str_equal(s, "foo") ) { return m_foo; } else if ( str_equal(s, "the_bar") ) { return m_bar; } else { return m_other.at(s); } } private: template<int N, int M> static constexpr bool str_equal(const char (&s)[N], const char (&s2)[M]) { if constexpr (N == 0 || N != M) return false; for(int i = 0; i < N; i++) { if (s[i] != s2[i]) return false; } return true; } int m_foo = 0; int m_bar = 0; boost::unordered_map<std::string, js_value_t> m_other; }; auto my_function(js_object& b) { b.set("the_bar", 1111); return std::get<int>(b.get("the_bar")); } auto other_function(js_object& b) { using namespace std::literals; b.set("random_value", "a string"s); }
Avec GCC à -O3, my_function se simplifie. my_function(js_object&): mov DWORD PTR [rdi+4], 1111 mov eax, 1111 ret
my_function
my_function(js_object&): mov DWORD PTR [rdi+4], 1111 mov eax, 1111 ret
AltStyle によって変換されたページ (->オリジナル) / アドレス: モード: デフォルト 音声ブラウザ ルビ付き 配色反転 文字拡大 モバイル
[^] # Re: Nouveau langage
Posté par jcelerier . En réponse à la dépêche C++17 branche à la compilation (`if constexpr`). Évalué à 1. Dernière modification le 06 décembre 2016 à 00:14.
En attendant, on peut tricher un peu en faisant ça :
Avec GCC à -O3,
my_functionse simplifie.my_function(js_object&):
mov DWORD PTR [rdi+4], 1111
mov eax, 1111
ret