具有不同主体的方法的模板显式实例化

Template explicit instantiation of a method with a different body

本文关键字:实例化 方法 主体      更新时间:2023-10-16

我有一个模板类,它有一个接受std::vector<T>的构造函数。对于除一个对象外的每一个对象,我都希望它进行操作A。但对于这一个对象来说,我希望它做一些其他的事情B。

是否有可能只为模板类创建构造函数的显式实例化?我希望它描述得足够准确。

问候

更新:我现在已经实现了一个测试用例:

//header
Container(const std::vector<T>& source)
{...}
//source code
template <> Container<int>::Container(const std::vector<int>& source)
{
    throw 42;
}

此示例可编译但不起作用。我将其导出到dll中,并希望每当我尝试用泛型参数int创建类的实例时都能调用它。但现在,它只调用用于其他所有对象的标准构造函数。我必须对申报单做些修改吗?

更新:我成功了!只需要将其复制到头文件中。

更新:好的,现在我有另一个问题。我能够为"简单"类型进行专门化,但不能为模板进行专门化。我是这样尝试的:

template<typename T>
Container<MyClass<T>>::Container(const std::vecror<MyClass<T>>& source)
{...}

我想为每个MyClass对象专门化它,但MyClass本身应该能够作为模板存在。

您的问题不清楚。也许你的意思是这样的?

template <typename T>
class Foo
{
public:
    Foo() { std::cout << "standard" << std::endl; }
};
template <>
Foo<float>::Foo() { std::cout << "random" << std::endl; }  // Special case
...
Foo<int>    f1;  // Prints "standard"
Foo<float>  f2;  // Prints "random"

哪个编译器?我在一些旧版本的g++编译器以及Solaris和HPUX c++编译器的模板实例化方面遇到了问题。template <>用于指定显式通知。我已经很久没有专门化只一个类的方法了。

你试过了吗?

template <> TemplateClass<InstanciedType>::TemplateClass()  {
   ...
}

其中,TemplateClass是要覆盖的模板类实例。

没有办法进行显式构造函数模板实例化——这里介绍了这一点:C++调用显式模板构造函数

如果我正确理解你的问题,你想这样做:

template< typename T >
struct A
{
  template< typename P >
  A( std::vector< P > &v )
  {
  }
};