首页 > 解决方案 > 模板参数的有效对象

问题描述

考虑以下代码:

  template <class T>
    T average(T *atArray, int nNumValues)
    {
        T tSum = 0;
        for (int nCount = 0; nCount < nNumValues; nCount++)
        {
            tSum += atArray[nCount];
        }
        tSum = tSum / nNumValues;
        return tSum;

}

以及关于它的以下问题:

以下关于类/类型 T 的哪些陈述必须为真,才能使代码编译和运行而不会崩溃?

  1. 它必须是某种数字类型
  2. 必须有 < 运算符定义
  3. 必须具有 [ ] 访问运算符定义的
  4. 必须有复制构造函数和赋值运算符



我的想法:
我认为它可能与数字类型不同,但需要明确定义运算符 + 和 /。
第 2 点似乎不正确,因为 < 与 / 和 + 运算符
与第 3 点和第 4 点相同。
虽然我不确定我上面的推理。

标签: c++

解决方案


  1. 否 - 例如,它可以与数字类型进行隐式转换并已operator+=定义。
  2. 否 - 该运算符未用于T
  3. 否 - 该运算符未在 a 上使用T,只有 aT*和指针类型都定义了该运算符。
  4. 否 - 复制构造函数可以是deleted 并且问题是“”,所以答案是否定的。不过,它需要某种赋值运算符。

考虑这门课,特别是为了能够对尽可能多的问题回答“否”:

struct foo {
    foo() = default;
    foo(int) {}                                   // implicit conversion from int
    
    foo(const foo&) = delete;                     // no copy constructor
    foo(foo&&) = default;                         // but move constructor
    foo& operator=(const foo&) = delete;          // no copy assignment
    foo& operator=(foo&&) = delete;               // no move assignment
    
    foo& operator=(int) { return *this; };        // but assignment from int

    foo& operator+=(const foo&) { return *this; } // for tSum += atArray[nCount];

    operator int() const { return 1; }            // implicit conversion to int
};

它可以与函数模板一起正常工作:

int main() {
    foo arr[2];

    auto x = average(arr, 2);
}

推荐阅读