c++ - Specializing a function from a variadic template class -


consider illegal code:

template <int... is> struct object {     void foo() const;     };  template <int... js> void object<0, js...>::foo() {/*do whatever*/} 

we want specialize foo() when first template parameter 0, , let's want specialize foo() if second parameter 3, , third int 1. solution found (not sure if best approach) following:

#include <iostream>  template <int...> struct foo;  template <int... is> struct object {     int id;  // member illustrate case when 'this' needed in foo().     friend struct foo<is...>;     void foo() const {foo<is...>::execute(this);}  // pass 'this' in case needed. };  template <int... is> struct foo<0, is...> {     static void execute (const object<0, is...>* object) {std::cout << "first int = 0, id = " << object->id << ".\n";} };  template <int n, int... is> struct foo<n, 3, is...> {     static void execute (const object<n, 3, is...>* object) {std::cout << "second int = 3, id = " << object->id << ".\n";} };  template <int m, int n, int... is> struct foo<m, n, 1, is...> {     static void execute (const object<m, n, 1, is...>* object) {std::cout << "third int = 1, id = " << object->id << ".\n";} };   int main() {     object<0,5,8,2>{4}.foo();     object<4,3,2,5,3>{2}.foo();     object<4,2,1>{0}.foo(); } 

first of all, solution good? next, problem arises if try object<0,3,1,4>{8}.foo(); because spec not complete. let's earliest matched specialized int take precedence. in case object<0,3,1,4>{8}.foo(); should run first specialization because of 0, while object<9,3,1,4>{8}.foo(); shall run second specialization because of 3, , forth. how enforce rule?

i suggest using if statements. compiler optimize them away anyway (assuming have optimization enabled).

in other words, this:

template <int... js> void object::foo() {     std::array<int, sizeof...(js)> args = {js...}; // _think_ correct syntax dump parameter pack std::array.     if(args.size() > 0 && args[0] == 0) {         // first argument 0, whatever.     } else {         // it's not 0, other thing.     } } 

you'll pretty same effect, , code quite bit clearer.


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -

How to provide Authorization & Authentication using Asp.net, C#? -