ورود

View Full Version : اشكال در Template



JalaliMehr
شنبه 30 مرداد 1389, 15:27 عصر
سلام.
يك كلاسي تعريف شده كه از Template استفاده مي كنه به صورت زير و هيچ مشكلي نداره.

// Test.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
using std::cout;
template <class T>
class Test
{
public:
void ShowMsg(T Value);
};
template <class T>
void Test<T>::ShowMsg(T Value)
{
cout<< Value;
}
int _tmain(int argc, _TCHAR* argv[])
{
Test<int> a;
a.ShowMsg(12);
return 0;
}




همين كلاسي كه از template استفاده كرده رو در يك فايل headerو ‍C++‎ مجزا پياده كردم مشكل مي گيره اشكال از چي مي تونه باشه


// Test.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "TetsCls.h"
int _tmain(int argc, _TCHAR* argv[])
{
CTetsCls<int> a;
a.ShowMsg(12);
return 0;
}


//TestCls.cpp
#include "StdAfx.h"
#include "TetsCls.h"
#include <iostream>
using std::cout;
template <class T>
CTetsCls<T>::CTetsCls(void)
{
}
template <class T>
CTetsCls<T>::~CTetsCls(void)
{
}
template <class T>
void CTetsCls<T>::ShowMsg(T Value)
{
cout << Value;
}



//TestCls.h
#pragma once
template <class T>
class CTetsCls
{
public:
CTetsCls(void);
~CTetsCls(void);
void ShowMsg(T Value);
};

JalaliMehr
دوشنبه 01 شهریور 1389, 08:15 صبح
سلام دوستان.
کسی نبود به این سوالمون جواب بده خیلی ممنون میشم اگه بگید مشکل کد دومم چیه که کامپایل نمیشه

Jaguar
دوشنبه 01 شهریور 1389, 16:55 عصر
Template ها شبیه توابع inline هستند و باید در همان جایی که به کار می روند تعریف گردند.
به جای پیاده سازی منطق در TestCls.cpp آن را در TestCls.h پیاده سازی کنید. و یا در یک هدر جدااگانه که آن را در این هدر و در آخرین سطر include می کنید.
راه حل سوم نیز include کردن یک فایل cpp. به جای آن هدر جداگانه است و اگر کامپایلر شما ایراد گرفت، فایل cpp. را در فایل اصلی include کنید و در آن فایل cpp. جدید (جداگانه) ، هدر را include کنید.
البته در استاندارد زبان کلمه کلیدی export پیش بینی شده ولی یکی دو تا کامپایلر بیش تر اون رو پشتیبانی نمی کنند و آینده اون نیز معلوم نیست.