简体   繁体   English

非模板类中的某些模板功能

[英]Certain template functions in non-template class

I'm trying to create a class, which will contain two pairs of template functions: one for char and one for wchar_t. 我正在尝试创建一个类,该类将包含两对模板函数:一个用于char,一个用于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 顺便说一句,您应该尝试使用范围和命名来对其有所了解: 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)
{
  ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM