问题
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,
^
回答1:
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>&);
回答2:
You cannot explicitly define the type for a template constructor.
Instead, they will be defined from the arguments.
As an example, consider the following code:
struct S {
template<typename T>
S(T t) { }
};
// ...
S s{'c'}
Here you don't actually require to specify the type and it is defined from the argument as char
.
来源:https://stackoverflow.com/questions/36166531/how-to-explicit-instantiate-template-constructor-in-c