Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to explicit instantiate template constructor in C++?

Currently I have the following class

//AABB.h
class AABB {
   public:
    template <class T>
    AABB(const std::vector<T>& verties);
    template <class T>
    AABB(const std::vector<int>& indicies, const std::vector<T>& verties);
    template <class T>
    AABB(const std::vector<int>::const_iterator begin,
         const std::vector<int>::const_iterator end,
         const std::vector<T>& verties);
    AABB();
    AABB(const vec3 min, const vec3 max);
    AABB(const AABB& other);

    const vec3& min_p() const { return m_min; }
    const vec3& max_p() const { return m_max; }

    vec3 center();
    float volume();
    float surface_area();
    bool inside(vec3 point);
    float intersect(const Ray& ray);

   private:
    vec3 m_min;
    vec3 m_max;
};

There are three AABB constructors that are templated. Is there a possible way I could declare use explicit instantiation? Like the following?

// AABB.cpp
template AABB::AABB<Triangle>(const idx_t, const idx_t, const vector<Triangle>&);

given

// AABB.cpp
using idx_t = std::vector<int>::const_iterator;

Currently the error from the compiler is

/Users/DarwinSenior/Desktop/cs419/tracer2/src/AABB.cpp:7:16: error: qualified
      reference to 'AABB' is a constructor name rather than a type wherever a
      constructor can be declared
template AABB::AABB<Triangle>(const idx_t, const idx_t,
               ^
like image 491
darwinsenior Avatar asked Aug 31 '25 04:08

darwinsenior


1 Answers

You're almost there, the problem is the last argument must be a reference as it's in the template declaration:

template AABB::AABB<Triangle>(const idx_t, const idx_t, const vector<Triangle>&);
//                                                                           ^^^

Also, as T.C pointed out, you can remove <Triangle> because it can be inferred from the type of the argument:

template AABB::AABB(const idx_t, const idx_t, const vector<Triangle>&);
like image 162
Anton Savin Avatar answered Sep 02 '25 16:09

Anton Savin