[英]how to solve following problem in C++?
我有一个模板函数,它将采用指针类型,并且在调用之前已实例化它。 我已经用其虚拟实现编写了函数,如下所示:
template<T>fun_name( const T *p )
{
//written functionality which will give me class name that i will store into string Variable
e.g. i got output like this string Var = "First_class" or string Var = "Second_class"
//Using this class name i will call one function of that class
if(Var == "Fisrt_class")
{
First_class::static_function_name(p);
}
if(Var == "Second_class")
{
Second_class::static_function_name(p);
}
}
在全局范围内,我为两个变量实例化了此函数,如下所示:
template<first_class>static_function_name(const First_class *)
template<Second_class>static_function_name(const Second_class *)
上面的代码给我错误
error: no matching function call in Second_class::static_function_class(const Fisrt_class*)
error: no matching function call in First_class::static_function_class(const Second_class*)
提前致谢!
我认为这 :
template<typename T> // template<class T> is equally valid!
void fun_name( const T *p )
{
T::static_function_name(p);
}
足够!
上面的代码修复了两个错误:
template<T>
中提及关键字typename
。 您还可以编写同样有效的template<class T>
。 您的函数模板“调用”每个类中的每个静态函数。 即使程序流可能永远不会到达其中一个调用,编译器仍必须找出每个调用的代码。
因此,当您实例化时:
template<first_class>fun_name(const first_class*)
编译器尝试使用T = first_class编译整个函数,这意味着在函数内部的某个时刻,它将尝试编译函数调用:
Second_class::static_function_name(p);
但是由于变量p
是指向first_class
的指针,所以编译器找不到该函数。
如果要进行条件编译,请尝试对函数进行专用化,以便编译器仅编译针对每种类型的函数调用:
template <T> fun_name (const T* p);
template <> fun_name<first_class>(const first_class* p) {
first_class::static_function_name(p);
}
template <> fun_name<second_class>(const second_class* p) {
second_class::static_function_name(p);
}
另外,您可以使用成员函数,这些成员函数似乎适合您在此处尝试做的事情。 然后,您可以创建对象并直接调用函数:
first_class f;
second_class s;
f.function();
s.function();
尝试更改为,
template<typename T>
void fun_name( const T *p )
{
T::static_function_name(p);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.