简体   繁体   English

C ++模板显式专业化-调用现有成员函数

[英]C++ template explicit specialization - calling existing member function

I'm using explicit template specialization to initialize a std::vector with information but only for a specific type of std::vector, thus the explicit specialization. 我正在使用显式模板专业化来初始化带有信息的std :: vector,但仅针对特定类型的std :: vector,因此是显式专业化。 Within the constructor, if I try to call push_back or any other existing function in std::vector, compilation fails. 在构造函数中,如果我尝试在std :: vector中调用push_back或任何其他现有函数,则编译将失败。 What is the problem and how do I fix it? 有什么问题,我该如何解决?

simplified example: 简化示例:

namespace std
{
  template<>
  class vector<int>
  {
  public:
    vector(void)
    {
      int value = 5;
      push_back(value);
    }
  };
}

compiler message: 编译器消息:

In constructor 'std::vector<int>::vector()':
error: 'push_back' was not declared in this scope
       push_back(value);
                      ^

Explicit specializations are completely different classes that are separate from the primary template. 显式专业是与主模板完全不同的类。 You have to rewrite everything. 您必须重写所有内容。

In normal situations where you control the primary template, you would typically have some sort of common base class or base class template to collect common structures. 在控制主模板的正常情况下,通常会使用某种通用基类或基类模板来收集通用结构。

With a given library, it is generally a very bad idea to add specializations (unless the library explicitly says it's OK). 对于给定的库,添加专业化通常是一个非常糟糕的主意(除非该库明确表示可以)。 With the C++ standard library, this is outright undefined behaviour. 使用C ++标准库,这是完全未定义的行为。

(The main problem is that other translation units may be using the template instantiation which you're specializing without seeing your specialization, which violates the one-definition rule.) (主要问题是其他翻译部门可能正在使用您要专门化的模板实例化而没有看到您的专门化,这违反了一个定义规则。)

Template specializations are unrelated types from both the primary template and any other specialization. 模板专业化是与主模板和任何其他专业化无关的类型。 It is unclear what you are attempting to do, as it is also illegal to provide specializations of templates in the std namespace unless the specialization uses your own user defined type. 目前尚不清楚您要做什么,因为在std名称空间中提供模板的特殊化也是非法的,除非特殊化使用您自己的用户定义类型。

If you can explain the problem to solve, you might get other options, like specializing a member function rather than the template itself... 如果您可以解释要解决的问题,则可能会获得其他选择,例如专门化成员函数而不是模板本身。

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

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