[英]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与“ class A”相同时才调用“ class A”的函数。 key_type can be char, int and 'class A'.
key_type可以是char,int和'class A'。 class A has its own function 'special_function_in_A' which int or char do not have.
类A有其自己的函数'special_function_in_A',而int或char没有。 It makes compile error.
它使编译错误。 How can I resolve it?
我该如何解决?
Thank you :D 谢谢: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: 其中
do_something_else
定义为:
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.