【问题标题】:How can a templated function modify it's behaviour at compilation time depending upon the type?模板函数如何根据类型在编译时修改其行为?
【发布时间】:2018-03-30 01:03:57
【问题描述】:
#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-&gt;attr

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

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

【问题讨论】:

    标签: c++ templates pointers compilation


    【解决方案1】:

    您可以使用Constexpr If(C++17 起),它在编译时有效。

    如果值为真,则丢弃statement-false(如果存在),否则丢弃statement-true。

    例如

    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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-23
      • 2019-11-10
      • 1970-01-01
      • 2019-04-23
      • 1970-01-01
      • 2010-12-12
      相关资源
      最近更新 更多