【问题标题】:template class with a single method specialized in C++具有一个专门用于 C++ 的方法的模板类
【发布时间】:2014-09-08 12:32:37
【问题描述】:

我只有一个用于C++学校作业的hpp文件(我不允许添加cpp文件,声明和实现都应该写在文件中)。

我在里面写了这段代码:

template<class T>
class Matrix
{
   void foo()
   {
       //do something for a T variable.
   }
};

我想添加另一个foo 方法,但是这个foo() 将专门用于&lt;int&gt;。 我在某些地方读到我需要声明一个新的专业化类才能使其工作。但我想要的是专门的foo 将位于原始foo 的下方,所以它看起来像这样:

template<class T>
class Matrix
{
   void foo(T x)
   {
       //do something for a T variable.
   }
   template<> void foo<int>(int x)
   {
       //do something for an int variable.
   }
};
  • 为什么我收到此语法的错误(“在 '
  • 为什么这不可能?
  • 如何在不声明新的专业类的情况下解决此问题?

谢谢

【问题讨论】:

  • foo 不是模板。 Matrix 是。
  • 您收到错误是因为这违反了 C++ 语法。您不能只专门化模板类的成员,而是需要专门化整个类。
  • 但是我在那个类中有很多其他函数,所以我必须将所有这些函数复制粘贴到新的“int”类中吗?听起来像是可怕的代码重复。
  • @40two:您只能专门化方法:参见 T.C.回答。
  • 您还可以将方法本身设为模板,并对方法本身进行特化。具体要求是什么时候?

标签: c++ templates template-specialization


【解决方案1】:

foo 不是模板。它是模板的成员函数。因此foo&lt;int&gt; 毫无意义。 (此外,必须在命名空间范围内声明显式特化。)

您可以显式特化类模板的特定隐式实例化的成员函数:

template<class T>
class Matrix
{
   void foo(T x)
   {
       //do something for a T variable.
   }
};

// must mark this inline to avoid ODR violations
// when it's defined in a header
template<> inline void Matrix<int>::foo(int x)
{
     //do something for an int variable.
}

【讨论】:

  • 太棒了。但是,是否允许在 hpp 文件中写入这一行: template void Matrix::foo(int x) ?因为我通常只在 cpp 文件中看到它。
  • @user2630165 是的,没关系……不过你需要做到inline
【解决方案2】:

你需要将原来的foo方法定义为模板,其实你的类不需要是模板,只要方法:

class Matrix
{
    template<typename T> void foo(T x)
    {
        //do something for a T variable.
    }
    template<> void foo<int>(int x)
    {
        //do something for an int variable.
    }
};

更新:该代码仅适用于 Visual Studio。这是一个也应该在其他地方工作的代码:

class Matrix
{
    template<typename T> void foo(T x)
    {
        //do something for a T variable.
    }
};

template<> void Matrix::foo<int>(int x)
{
    //do something for an int variable.
}

【讨论】:

  • 无法编译:error: explicit specialization in non-namespace scope 'class Matrix'...
  • 没错,我写的代码只兼容visual studio。我添加了一个兼容 C++ 的代码,它也应该适用于 GCC。
  • 我很确定 OP 需要 Matrix 作为模板。
  • OP 明确写道,他们需要另一个专门用于 int 的 foo 方法。
  • 我很确定Matrix 类需要存储一些类型可能不同的数据...
猜你喜欢
  • 2013-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-21
  • 1970-01-01
相关资源
最近更新 更多