簡體   English   中英

如何解決C ++中的以下問題?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM