C ++虚拟方法的部分模板专业化

时间:2015-03-18 09:14:00

标签: c++ templates c++11 template-specialization

我有一个简单的基类Shape及其派生类Ball。目的是在标量类型和维度上具有通用性,从而使用模板。

#include <iostream>
#include <array>
#include <cmath>

template<typename T, std::size_t DIM>
class Shape {
public:
    Shape(std::array<T,DIM> base_point) : base_point_(base_point) {}
    virtual T volume() const = 0;
protected:
    std::array<T,DIM> base_point_;
};

template<typename T, std::size_t DIM>
class Ball : public Shape<T,DIM> {
public:
    Ball(std::array<T,DIM> base_point, T radius) : Shape<T,DIM>(base_point), radius_(radius) {}
    virtual T volume() const;
private:
    T radius_;
};

// Cannot use the generic code below because of Template may not be 'virtual' ?
// template<typename T>
// T Ball<T,2>::volume() const { return M_PI * radius_ * radius_; }

template<>
float Ball<float,2>::volume() const { return M_PI * radius_ * radius_; }

// template<typename T>
// T Ball<T,3>::volume() const { return 4/3 * M_PI * radius_ * radius_ * radius_; }

template<>
float Ball<float,3>::volume() const { return 4/3 * M_PI * radius_ * radius_ * radius_; }

int main() {
    Ball<float,2> circle{{0.2f,0.3f}, 4.0f};
    std::cout << circle.volume() << std::endl;
}

我想使用部分模板专门化来计算取决于维度的音量。代码可以工作但是很麻烦,如果我必须专门研究另一种类型,比如double(代码会是相同的)。

我知道我不能对虚拟方法进行部分模板专业化,但是当我使用上面注释的代码时,我有以下错误而不是错误:模板可能不是'虚拟'

shape_generic_naive.cpp:24:25: error: invalid use of incomplete type ‘class Sphere<T, 2ul>’
 T Sphere<T,2>::volume() const {return M_PI * radius_ * radius_; }
                         ^
shape_generic_naive.cpp:15:7: error: declaration of ‘class Sphere<T, 2ul>’
 class Sphere : public Shape<T,DIM> {

我真的没有得到这个错误,如何避免它以及有什么方法可以优雅地获得这种通用性?

1 个答案:

答案 0 :(得分:3)

几乎总是,如果你需要功能模板部分特化,你可以使用&#34;委托给类&#34;特技:

template <class T, std::size_t DIM>
struct BallVolume;

template <class T>
struct BallVolume<T, 2>
{
  static T compute(T radius) { return M_PI * radius * radius; }
};

template <class T>
struct BallVolume<T, 3>
{
  static T compute(T radius) { return 4.0/3.0 * M_PI * radius * radius * radius; }
};


template<typename T, std::size_t DIM>
class Ball : public Shape<T,DIM> {
public:
    Ball(std::array<T,DIM> base_point, T radius) : Shape<T,DIM>(base_point), radius_(radius) {}
    virtual T volume() const { return BallVolume<T, DIM>::compute(radius_); }
private:
    T radius_;
};

请注意,您的3D音量公式不正确:4/31,因为它是整数除法。

另外,为了保持它真正的类型中性,你应该将常量转换为T

return static_cast<T>(M_PI) * radius * radius;
return 4 / static_cast<T>(3.0) * static_cast<T>(M_PI) * radius * radius * radius;
相关问题