简体   繁体   中英

How can I specialize template function for a type in Parameter lists

My code snippet follows...

struct ParameterLists1 {
 typedef int key_type;
 typedef char value_type;
}

class A { ~~ };

struct ParameterLists2 {
 typedef A key_type;
 typedef int value_type;
}

template<P>
class Mine {
 typedef typename P::key_type key_type;
 typedef typename P::value_type value_type;

 void foo(key_type k, value_type v) {
       ~~ do something ~~
   if key_type is 'class A'
       key.special_function_in_A (k);
 }
 private:
   key_type key;
   value_type val;
}

I'd like to make call a function of 'class A' only when the key_type is the same with 'class A'. key_type can be char, int and 'class A'. class A has its own function 'special_function_in_A' which int or char do not have. It makes compile error. How can I resolve it?

Thank you :D

Use tag-dispatching. The call site would look like this:

~~ do something ~~
do_something_else(key, k, std::is_same<key_type, A>());

Where do_something_else is defined as:

template<typename T>
void do_something_else(key_type&, key_type&, std::false_type) { }

template<typename T>
void do_something_else(key_type& key, key_type& k, std::true_type)
{
    key.special_function_in_A(k);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM