【问题标题】:Method for two different types in template class C++模板类C++中两种不同类型的方法
【发布时间】:2018-03-29 21:12:12
【问题描述】:

我想做某种专业化,像这样:

template <typename Type, int Size>
class Example
{
//some values
public:
double length() const;
}

template <typename Type, int Size>
double Example<double, Size>::length() const {...}

template <typename Type, int Size>
double Example<MyType, Size>::length() const {...}

显然它不起作用。我应该如何实现这个方法?我希望 Type 被显式声明并且 Size 在这里是可变的。

【问题讨论】:

  • 这些模板参数在哪里使用? Size 真的需要成为类型的一部分吗?
  • 你应该只专注于这个类:template &lt;int Size&gt; class Example&lt;double, Size&gt; { public: double length() const { /* ... */ } };
  • 我在 for 循环中使用 Size,它必须是类型的一部分,它在标题中定义。任何定义都不使用类型。
  • 或者您也可以使用 CRTP 仅专门化一小部分...
  • 好的,那么,你的意思是什么?它仍然是类型的一部分,只有 Type 是特化的。

标签: c++ oop templates


【解决方案1】:

一种选择是专门针对doubleMyType 的类模板。

template <typename Type, int Size>
class Example
{
  public:
    double length() const { /* Use a generic implementation */ }
}

// Specialize for double
template <int Size>
class Example<double, Size>
{
  public:
    double length() const { /* Use a double specific implementation */ }
}

// Specialize for MyType
template <int Size>
class Example<MyType, Size>
{
  public:
    double length() const { /* Use a MyType specific implementation */ }
}

另一种选择是使用另一个模板类/函数,可以被Example::length() 的通用实现使用。

template <typename Type, int Size>
struct Length
{
   // Generic implementation
   static double get() { ... }
}

// Specialize Length for double and MyType

template <int Size>
struct Length<double, Size>
{
   static double get() { ... }
}
template <int Size>
struct Length<MyType, Size>
{
   static double get() { ... }
}

template <typename Type, int Size>
class Example
{
  public:
    double length() const { return Length<Type, Size>::get(); }
}

如果Example 中的所有其他内容,但length 成员函数可以使用通用代码实现,则第二种方法会更好。

【讨论】:

  • 我的班级已经有很多方法,但只有一个取决于类型,在这里专门化整个班级似乎并不有效。第二种方法很棒,谢谢!
猜你喜欢
  • 2014-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-09
  • 1970-01-01
相关资源
最近更新 更多