I'm trying to create a class, which will contain two pairs of template functions: one for char and one for wchar_t. I wrote the following code, but it couldn't be built because linker cannot find realizations of functions. I think the problem is that linker thinks the functions in the class are not the instantiations of template ones.
How can I define the functions needed?
template<typename T>
int func1(const T* szTarget)
{
...
}
template<typename T>
T* func2(const T* szTarget)
{
...
}
class MyClass
{
public:
int func1(const char* szTarget);
int func1(const wchar_t* szTarget);
char* func2(const char* szTarget);
wchar_t* func2(const wchar_t* szTarget);
};
Actually you're defining two template function outside the scope of your class, they are not related with your class by any way.
So why not just :
class MyClass
{
public:
template<typename T>
int func1(const T* szTarget)
{
/* ... */
}
template<typename T>
T* func2(const T* szTarget)
{
/* ... */
}
};
By the way, you should experiment with scopes and naming to understand it a bit: http://ideone.com/65Mef5
What about
class MyClass {
public:
template<typename T>
int func1(T* szTarget) {
// provide appropriate implementation
}
template<typename T>
char* func2(T* szTarget) {
// provide appropriate implementation
}
};
The compiler is right.
You have to declare the template functions as members of the class. Which means they need to be declared inside the class declaration.
class MyClass
{
public:
template<typename T>
int func1(const T* szTarget)
{
...
}
template<typename T>
T* func2(const T* szTarget)
{
...
}
template <> int func1(const char* szTarget) { } //specialization
template <> int func1(const wchar_t* szTarget) { } //specialization
template <> char* func2(const char* szTarget) { } //specialization
template <> wchar_t*func2(const wchar_t* szTarget) { } //specialization
};
You haven't defined any templated methods in your class. One way of doing it is as follows:
class MyClass
{
public:
template <typename T> int func1(const T* szTarget);
template <typename T> T* func2(const T* szTarget);
};
template<typename T>
int MyClass::func1<T>(const T* szTarget)
{
...
}
template<typename T>
T* MyClass::func2<T>(const T* szTarget)
{
...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.