【问题标题】:C++ template class - inheritance calling wrong functionC++ 模板类 - 继承调用错误的函数
【发布时间】:2020-10-02 19:20:32
【问题描述】:

我想停止调用基本“int”函数。我想用“double”调用继承

#include <iostream>
using namespace std;

template<typename T, size_t N>
class A {
public:

};

template<size_t N>
class A<int, N> {
public:
void push(const int& val)             
 {
    cout << val << endl;
 }
};

template<size_t N>
class A<double, N>
: public A<int, N>
{
public:

};


int main() {
A<double, 8> r;
r.push(5.7);
return 0;
}

警告给了我从 double 到 int 的隐式转换。如何防止使用 int 调用函数?

编辑: 我想在排序或处理过程中使用专业化并将整数、双精度和浮点数视为 NUMBERS,并以不同的方式处理字符串。这就是为什么我想使用专业化。由于数字算法相同,我试图继承双精度和浮点数,我只是想在继承后更改数据类型并保持“推送”等其他功能仍然可用。基本上总共节省了 5k 行。

【问题讨论】:

  • 您的代码中没有采用double 的函数。
  • 所以没有办法只用推导来“重写”吗?并使用 double 而不是 int?
  • 重写它?继承时不会重写任何内容。基地的成员仍然是基地的相同的成员。
  • 你为什么在这里使用推导?还是专业?你想解决什么问题?
  • 为什么不在主模板中写void push(const T&amp; val),去掉专业化?

标签: c++ function templates inheritance containers


【解决方案1】:

根据您的问题,我了解到您需要不同版本的 push,具体取决于 T

您可以为此使用元编程。

#include <type_traits>

template<typename T, size_t N, typename = void>
class A {
  public:
    void push(const T& value) {
      // General version
    }
};

template<typename T, size_t N>
class A<T, N, std::enable_if_t<
                   std::is_intergral<T>::value ||
                   std::is_floating_point<T>::value>>> {
  public:
    void push(const T& value) {
        // Integral & floating point version
    }
};

【讨论】:

  • is_numeric 不是标准特征。您可能指的是is_arithmetic(巧合的是,它已经涵盖了浮点类型)。
  • 我是想写std::is_integral,我编辑了答案。
  • 哇,谢谢你的回答!我只是在问......如果不使用 std 中的工具,还有其他方法吗?
  • 谢谢大家的回答:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-20
  • 1970-01-01
  • 2020-01-23
  • 2012-10-05
  • 1970-01-01
相关资源
最近更新 更多