如何解决C ++中的以下问题?

时间:2011-03-10 06:06:00

标签: 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*)

提前感谢!

3 个答案:

答案 0 :(得分:1)

我想这个:

template<typename T> // template<class T> is equally valid!
void fun_name( const T *p )
{
  T::static_function_name(p);
}

就够了!

上述代码中还修复了两个错误:

  • 在代码中的typename中提及关键字template<T>。您也可以撰写同等有效的template<class T>
  • 同时提及功能模板的返回类型。

答案 1 :(得分:0)

您的函数模板“调用”每个类中的每个静态函数。即使程序流可能永远不会进入其中一个调用,编译器仍然需要为每个调用找出代码。

所以当你实例化时:

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();

答案 2 :(得分:-1)

尝试改为,

template<typename T>
void fun_name( const T *p )
{
  T::static_function_name(p);
}
相关问题