简体   繁体   English

为模板功能专门化模板类

[英]specialize a template class for a template function

I have two template classes like 我有两个模板类

template <class T>
class MyClass1{};

template <class T>
class MyClass2{};

and I have a template function using them as an argument. 我有一个使用它们作为参数的模板函数。 The classes are specialized with std::string: 这些类专用于std :: string:

template <template class<std::string> T> myMethod(T<std::string>& arg){}

I'd like to use myMethod(objectOfMyClass1) and myMethod(objectOfMyClass2), but the code doesn't compile. 我想使用myMethod(objectOfMyClass1)和myMethod(objectOfMyClass2),但是代码无法编译。 How to specialize a template class for a template function? 如何专门针对模板函数使用模板类?

First, if your method does not take any arguments, you won't be able to call it as you want. 首先,如果您的方法没有任何参数,则将无法根据需要调用它。

Second, MyClass1 and MyClass2 are not classes but class templates -- you cannot therefore have objectOfMyClass1 and objectOfMyClass2 . 其次, MyClass1MyClass2不是类,而是类模板-因此,您不能拥有objectOfMyClass1objectOfMyClass2

If you your function to behave specially for an argument of any type of the form SomeClassTemplate<std::string> , then what you're after is partial function template specialization, which is not allowed in C++. 如果您的函数专门针对SomeClassTemplate<std::string>形式的任何类型的参数运行,那么您所追求的只是部分函数模板专门化,这在C ++中是不允许的。 You will have to use a partially-specialized class instead: 您将不得不使用部分专门的类:

template <class T>
struct MyMethodCall;

template <template <typename> class T>
struct MyMethodCall<T<std::string> > {
  static void call(T<std::string> object) {
    ...
  }
};

template <class T>
void myMethod(T & object) {
  MyMethodCall<T>::call(object);
}

This is a compilable example 这是一个可编译的示例

template <class T>
class MyClass1{};

template <class T>
class MyClass2{};

template <template <typename> class T> 
void myMethod(T<std::string>& arg){}

int main()
{
MyClass1<std::string> c1;
myMethod(c1);
MyClass1<std::string> c2;
myMethod(c2);
}

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

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