成员函数的 C++ 模板特化

标签 c++ templates member specialization

我正在尝试实现一个非常基本的 Vector3 ( Vec3 ) 类。 我正在为一个特例而苦苦挣扎: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 之间的公共(public)类型,即结果的模板参数。 这是一个可能的解决方案:

/// 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] };
}

关于成员函数的 C++ 模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31118886/

相关文章:

c++ - 在两个相同类的指针之间进行转换的安全性?

c++ - 如何调用模板类型的正确构造函数?

python - 从特定目录继承的 Django 加载模板

python - 从枚举中获取所有值,当值在 Python 3.7 中是可调用的

c++ - 模板类的成员函数,将模板类型作为参数

C++ 标准模板库优先级队列抛出异常,消息为 "Invalid Heap"

此类的 C++ 特征示例

C++ - 通过复制行为返回

c++ - 编译器如何在具有数组的模板特化之间进行选择?

C++:这是一个有效的常量成员函数吗?