vendredi 15 juin 2018

Capture caller source line with template parameters deduction

I need to capture the caller source line for a templated addition operator. The code below works fine without templates but complains about dependent type when templates are used.

I'm looking for any workaround or hack that can enable me to execute the simple add operation below and report the caller source line in C++.

#include <iostream>

template <unsigned N>
class widget {
  int data_;
public:
  class proxy {
  public:
    proxy(widget &a, int l = __builtin_LINE()) : a(a), l(l) {}
    widget &a;
    int l;
  };
  widget(int data) : data_(data << N) {}
  template <unsigned M>
  widget operator+(const typename widget<M>::proxy &other) {
    std::cout << "operator+ called at line " << other.l << std::endl;
    return widget((data_ >> N) + (other.a.data_ >> M));
  }
};

int main() {
  widget<2> x(5);
  widget<3> y(6);
  auto z = x + y;
  return 0;
}

compiler error: "template argument deduction/substitution failed"





Aucun commentaire:

Enregistrer un commentaire