visual c++主函数模板错误

visual c++ Template error in main function?

本文关键字:错误 函数模板 c++ visual      更新时间:2023-10-16

我正在使用vsc++ 6.0。我读到6.0有一些模板的问题??

好吧…如果我将声明保留为:

template <class T> T jMin( T a, T b ){
    return ( a < b );
}

函数工作,但做以下操作,我得到错误:

error C2039: 'jMin' : is not a member of 'CVid3Dlg'

为什么有区别?这可能与之前的帖子有关…

如果我把定义放在HEADER中,如下所示,我得到:

error C2893: Failed to specialize function template 'T __thiscall CVid3Dlg::jMin(T,T)'
        With the following template arguments:
        'double'
//CVid3Dlg.h

class CVid3Dlg : public CDialog
{
public:
    CVid3Dlg(CWnd* pParent = NULL); // standard constructor
    template <typename T>  T jMin( T a, T b );
protected:
    HICON m_hIcon;
    bool PreViewFlag;
    BITMAP bm; //bitmap struct
    CBitmap m_bmp; //bitmap object
    CRect m_rectFrame; //capture frame inside main window
    bool firstTime;

    // Generated message map functions
    //{{AFX_MSG(CVid3Dlg)
    virtual BOOL OnInitDialog();
    afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
    afx_msg void OnPaint();
    afx_msg HCURSOR OnQueryDragIcon();
    afx_msg void OnTimer(UINT nIDEvent);
    afx_msg void GetVideo();
    afx_msg void OnClose();
    afx_msg void testing();
    afx_msg void Imaging();
    afx_msg void exTemplate();
    //}}AFX_MSG
    DECLARE_MESSAGE_MAP()
};
//CVid3Dlg.cpp

template <class T> T CVid3Dlg::jMin( T a, T b ){// <-- FAILS
    return ( a < b );
}
void CVid3Dlg::exTemplate()
{
    Image *im = new Image();
    int s=0;
    s = jMin((double)3, (double)4);
    CString s1;
    s1.Format("%d", s);
    MessageBox(s1);
}

这个错误会告诉你哪里出错了:

'jMin' : is not a member of 'CVid3Dlg'

如果你写

template <class T> T CVid3Dlg::jMin( T a, T b ) { ... }

代替

template <class T> T jMin( T a, T b ) { ... }

则表示jMinCVid3Dlg的成员函数。如果你没有这样声明你就会得到这个错误

如果你想让jMin成为CVid3Dlg的模板成员函数,你必须把模板定义放在类CVid3Dlg中。

class CVid3Dlg
{
     template <class T> T jMin( T a, T b ){  
      return ( a < b );// ? a : b;  
     }     
};

好了,您已经使模板成为CVid3Dlg的成员函数。现在在CVid3Dlg::exTemplate()中,你可以这样使用它:

 CVid3Dlg::exTemplate() 
 {
       double min = jMin<double>(3.0, 3.1);
 }