c++ Template error in main function?

2019-09-19 15:38发布

I am using VS c++ 6.0. I have read that 6.0 has some problems with templates??

OK... if I leave the declaration as:

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

The function works, but doing as the following I get the error:

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

Why is there a difference?... and this may relate to the previous post...

If I put the definition in the HEADER as follows, I get:

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

3条回答
Juvenile、少年°
2楼-- · 2019-09-19 15:40

Well, the error tells you exactly what's wrong:

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

If you write

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

instead of

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

then you are saying that jMin is a member function of CVid3Dlg. If you haven't declared it like that then you'll get that error.

查看更多
Animai°情兽
3楼-- · 2019-09-19 15:40

If you want jMin to be a template member function of CVid3Dlg, you have to put the template definition inside the class CVid3Dlg.

class CVid3Dlg
{
     template <class T> T jMin( T a, T b ){  
      return ( a < b );// ? a : b;  
     }     
};
查看更多
虎瘦雄心在
4楼-- · 2019-09-19 15:54

OK, you've made the template a member function of CVid3Dlg. Now in CVid3Dlg::exTemplate() you can use it as follows:

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

 }
查看更多
登录 后发表回答