如何在C++中的模板类/结构体中实例化模板构造函数

问题描述 投票:0回答:1

我有一个带有模板构造函数的模板结构:

template<typename F>
struct Vector2
{
    template<typename F1>
    Vector2(const Vector2<F1>& vector);
};

实施:

template<typename F>
template<typename F1>
Vector2<F>::Vector2(const Vector2<F1>& vector)
: Vector2(vector.x, vector.y)
{}

可以为 Vector2 和 Vector2 类型中的 float 和 double 类型实例化此构造函数吗? 我试过:

template struct Vector2<float>::Vector2(const Vector2<float>& vector);
// Errors: "Expected unqualified-id" and "Expected ')'"
template struct Vector2<float>::Vector2<float>(const Vector2<float>& vector);
// Errors: same as in the previous one
template struct Vector2::Vector2(const Vector2<float>& vector);
// Error: "Use of class template 'Vector2' requires template arguments"
c++ templates constructor
1个回答
0
投票

如果你想显式实例化类模板

template struct Vector2<float>;

如果你想显式实例化一个类成员模板

template Vector2<float>::Vector2(const Vector2<float>& vector);
© www.soinside.com 2019 - 2024. All rights reserved.