此討論為其他討論串的延續: C++問題-函數不同實作的統一介面
原始問題為如何用C++實作一個計算向量2-norm的函數,這個函數會根據向量的型態而有不同的實作。
我從別人那裡發現了一個只需要定義一個函數實作的解法
template<typename T>
struct remove_complex {
using type = T;
};
template<typename T>
struct remove_complex<std::complex<T>> {
using type = T;
};
template<typename T>
using remove_complex_t = typename remove_complex<T>::type;
template<typename T>
void norm2(const T* a, const size_t length, remove_complex_t<T>& res) {
res = remove_complex_t<T>{0};
for (size_t i = 0; i < length; ++i) {
res += std::abs(a[i] * std::conj(a[i]));
}
res = std::sqrt(res);
}
雖然函數的實作只需要定義一次,不過這個方法還是需要定義兩個不同的struct
來提取不同場景(實數和複數)時所對應的實數型態,不是很確定在實務上這個方法跟前一個方法(針對不同場景,定義不同函數的實作)相比有什麼優勢?