[英]c++ universal templated class arithmetic
假設我們正在處理一個由於某種原因必須進行一些算術運算的類。
像tensor_sum
這樣的操作有重載的操作符模板。 這種方法的問題似乎是這樣的:
g++ main.cpp -o main
main.cpp: In instantiation of ‘tensor_sum<T0, T1>::value_type&
tensor_sum<T0, T1>::operator()(unsigned int) const [with T0 = tensor<int>; T1 = tensor<int>; tensor_sum<T0, T1>::value_type = int; typename T0::value_type = int; typename T1::value_type = int]’:
main.cpp:46:20: required from here
main.cpp:11:63: error: no match for call to ‘(const tensor<int>) (unsigned int&)’
value_type & operator () (unsigned int i) const { return t0_(i) + t1_(i); }
~~~^~~
main.cpp:32:7: note: candidate: T& tensor<T>::operator()(unsigned int) [with T = int] <near match>
T & operator () (unsigned int i) { return values_[i]; }
^~~~~~~~
main.cpp:32:7: note: passing ‘const tensor<int>*’ as ‘this’ argument discards qualifiers
main.cpp:11:72: error: no match for call to ‘(const tensor<int>) (unsigned int&)’
value_type & operator () (unsigned int i) const { return t0_(i) + t1_(i); }
~~~^~~
main.cpp:32:7: note: candidate: T& tensor<T>::operator()(unsigned int) [with T = int] <near match>
T & operator () (unsigned int i) { return values_[i]; }
^~~~~~~~
main.cpp:32:7: note: passing ‘const tensor<int>*’ as ‘this’ argument discards qualifiers
出於某種原因,我無法訪問該值。 但是我重載了() operator
無論如何這里是代碼:
#include <iostream>
#include <vector>
template<typename T0, typename T1>
struct tensor_sum {
typedef decltype(typename T0::value_type() + typename T1::value_type()) value_type;
public:
tensor_sum(const T0 &t0, const T1 &t1) : t0_(t0), t1_(t1) {}
value_type & operator () (unsigned int i) const { return t0_(i) + t1_(i); }
private:
const T0 &t0_;
const T1 &t1_;
};
template<typename T0, typename T1>
tensor_sum<T0, T1> operator + (const T0 &t0, const T1 &t1) { return tensor_sum<T0, T1>(t0, t1); }
template<typename T0, typename T1>
tensor_sum<T0, T1> operator + (const T0 &t0, const T1 &t1);
template<typename T>
struct tensor {
typedef T value_type;
public:
tensor(const unsigned int s = 0) : size_(s), values_(std::vector<T>(s)) {}
tensor(const tensor<T> &t) : size_(t.size_), values_(std::vector<T>(t.values_)) {}
T & operator () (unsigned int i) { return values_[i]; }
tensor<T> & operator = (const tensor<T> &t) { return tensor<T>(t); }
private:
const unsigned int size_;
std::vector<T> values_;
};
int main() {
tensor<int> t0(10);
tensor<int> t1(10);
tensor_sum<tensor<int>, tensor<int>> ts = t0 + t1;
std::cout << ts(2) << std::endl; //Can't access value.. why?
return 0;
}
tensor_sum<T0, T1> operator + (const T0 &t0, const T1 &t1);
返回一個 tensor_sum 並且 tensor 沒有帶有 tensor_sum 的 operator=。
所以你的代碼意味着 t0 + t1 返回一個 tensor_sum 並嘗試分配給一個張量,當然會失敗。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.