簡體   English   中英

成員函數的C ++模板專業化

[英]C++ template specialization for member function

我正在嘗試實現一個非常基本的Vector3Vec3 )類。 我正在努力處理一個特例: Vec3<size_t>Vec3<int>

如何針對這種情況進行模板專業化?

任何幫助,將不勝感激。

#include <array>
#include <ostream>
#include <vector>

// #define Vec3f std::array<float, 3>
// #define Vec3u std::array<size_t, 3>

#define Vec3f Vec3<float>
#define Vec3u Vec3<size_t>
#define Vec3i Vec3<int>

template <typename T>
class Vec3
{
    public:
        Vec3(): _a() {}
        Vec3(T x, T y, T z): _a({x, y, z}) {}
        Vec3(const Vec3<T> & a): _a({a[0], a[1], a[2]}) {}

        ~Vec3() {}

        /// Print Vec3.
        friend std::ostream & operator<<(std::ostream & os, const Vec3<T> & v)
        {
            os << "(" << v[0] << ", " << v[1] << ", " << v[2] << ")";
            return os;
        }

        inline typename std::array<T, 3>::reference operator[](size_t i)
        {
            return _a[i];
        }

        inline typename std::array<T, 3>::const_reference operator[](size_t i) const
        {
            return _a[i];
        }


        /// Test equality.
        inline bool operator==(const Vec3<T> & other) const
        {
            bool a = abs(_a[0] - other._a[0]) < 1e-6;
            bool b = abs(_a[1] - other._a[1]) < 1e-6;
            bool c = abs(_a[2] - other._a[2]) < 1e-6;
            return (a and b and c);
        }

        /// Test non-equality.
        inline bool operator!=(const Vec3<T> & other) const
        {
            return not (*this == other);
        }


        /// Vec3 same type addition.
        inline Vec3<T> operator+(const Vec3<T> & other) const
        {
            return {_a[0] + other[0], _a[1] + other[1], _a[2] + other[2]};
        }


    protected:
        std::array<T, 3> _a;
};

您的問題是在size_tint之間找到通用類型,該通用類型是結果的模板參數。 這是一個可能的解決方案:

/// Vec3 addition between vectors of different base type.
template <class U>
Vec3<typename std::common_type<T, U>::type> operator+(const Vec3<U> & other) const
{
    return{ _a[0] + other[0], _a[1] + other[1], _a[2] + other[2] };
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM