c++ - 模板函数如何根据类型在编译时修改它的行为?

标签 c++ templates pointers compilation

#include <iostream>
#include <vector>

class A
{
public:
   int attr;
   A(int a):attr(a){}
};

template <typename T>
int sum(std::vector<T> x)
{
  int s = 0;
  for (auto& elem : x)
  {
      s += elem.attr; // Problem is here, when elem is a pointer
  }
  return s;
}

int main()
{
   std::vector<A> x1 = {1,2,3,4,5};
   std::cout << "sum = " <<  sum(x1) << "\n";

   std::vector<A*> x2;
   for (auto& elem : x1)
     x2.push_back(&elem);

   std::cout << "sum = " <<  sum(x2) << "\n"; // Problem is this function call

   return 0;
}

以上不会编译为 elem.attr未定义 A* .应该是elem->attr .

有没有办法让这项工作无需重写整个函数sum

当然,sum是一个非常小的功能,但对于更大的功能,复制粘贴长代码开始成为一个设计问题。我会很想使用 if (std::is_pointer<elem>::value)但当然,这并不能解决问题,因为评估是在运行时而不是编译时进行的。

最佳答案

您可以使用 Constexpr If (C++17 起),在编译时工作。

If the value is true, then statement-false is discarded (if present), otherwise, statement-true is discarded.

例如

if constexpr (std::is_pointer_v<T>) {
    s += elem->attr; // when elem is a pointer
} else {
    s += elem.attr;  // when elem is not a pointer
}

关于c++ - 模板函数如何根据类型在编译时修改它的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49567104/

相关文章:

C++ setenv 解析其他变量

c++ - 如果输入了某些内容,我如何进行倒计时以每秒检查一次,而不会中断

c - 数组连接函数返回乱码。

c++ - 使用自己的模板所有者 ptr 类分配多维数组

c++ - 似乎无法让我的 IF 语句正常工作

c++ - 在编译 boost 时定义 BOOST_DISABLE_ABI_HEADERS 会带来什么危害?

templates - 提升 mpl 计数作为简单示例

c++ - typedef-name 作为基类 : illegal but widely tolerated

c++ - 在编译时检测是否存在默认构造函数

c - 接受结构指针并返回结构指针的函数有奇怪的行为?