C++如何用模板指定或其他方式实现
C++ how to implement with template specilization or other manner?
我正在实现一个Boundary-Volumn层次结构,其中树有一个这样的模板:
template <typename Coordinate>
class BoundingTree { /* ... */ }
Coordinate
可以是Vector2d
、Vector3f
或任何其他任意坐标。要使用这种BoundingTree
结构进行碰撞检测,应该有一个检测功能:
template <typename Coordinate>
template <typename RigidBody>
bool BoundingTree::collide(RigidBody const & body);
RigidBody
可以是一切,例如Cuboid3f
、Circle2d
。我对这个检测系统的实现是:
// BoundingTree.h
template <typename Coordinate>
class BoundingTree
{
public:
BoundingTree() {}
// collide function decleration
template <typename RigidBody>
bool collide(RigidBody const & obj);
};
// BoundingTree.cpp
// specilizations
template<typename Coordinate> template <typename RigidBody>
bool BoundingTree::collide(RigidBody const & obj)
{
std::cout << "default" << std::endl;
return false;
}
template<> template<>
bool BoundingTree<Vector3f>::collide<Sphere3f>(Sphere3f const & d)
{
std::cout << "Vector3f Sphere3f" << std::endl;
return 1;
};
template<> template<>
bool BoundingTree<Vector3f>::collide<Cuboid3f>(Cuboid3f const & d)
{
std::cout << "Vector3f Cuboid3f" << std::endl;
return 1;
};
但我得到了一个错误:
1>BoundingTree.cpp(6): error C2955: 'BoundingTree': use of class template requires template argument list
1> BoundingTree.h(32): note: see declaration of 'BoundingTree'
1>BoundingTree.cpp(10): error C2244: 'BoundingTree::collide': unable to match function definition to an existing declaration
1> BoundingTree.cpp(6): note: see declaration of 'BoundingTree::collide'
如何解决这个问题?
有没有更好的方法来实现这种任意类型的碰撞检测系统?
非常感谢。
您尝试做的是允许的,但您有语法错误,如下所示:
template<typename Coordinate> template <typename RigidBody>
bool BoundingTree::collide(RigidBody const & obj)
^
这不是一个专门化,所以你必须为类指定模板参数,它应该是
bool BoundingTree::collide<Coordinate>(...)
但我看到您的代码被分为头和源代码,这可能会造成代码的非专业化问题。
如果一个模板化函数是在源文件中定义的,但在另一个翻译单元中使用,那么在编译过程中不会生成模板的实例化,并且会出现链接器错误。
像这样的完全专业化不会发生这种情况
template<> template<>
bool BoundingTree<Vector3f>::collide<Sphere3f>(Sphere3f const & d)
但是,如果你计划进行部分专业化,那么你将被迫移动头文件中的所有内容,或者强制在定义它们的源文件中实例化模板,例如
template class BoundingTree<MyCoord>;
template bool BoundingTree<MyCoord>::collide<MyShape>(MyShape const& d);
相关文章:
- 我如何在一个 if 语句中声明所有数字我尝试通过其他方式声明所有数字,如果一个接一个,但似乎代码有逻辑错误
- 我如何使用“ op parallel”或其他方式并行循环
- 无法以正确的方式执行其他程序
- 类定义中定义的成员函数的编译方式是否与C++中其他位置定义的成员函数不同
- 实时在语言之间流水线传输或以其他方式传输数据
- 如何根据其ARITY(或编译时已知的其他信息)以不同的方式调用函数对象
- 如何通过Visual Studio COM包装(或其他方式)在C#中使用C++属性联合
- visual在源代码中是否有预定义的#define或其他方式来了解它是为C++/CX Windows运行时编译的
- C++ 如何通过可选的typedef,使用SFINAE或其他方式选择类
- 在C++中,函数在main()中更改变量的任何其他方式
- C++如何用模板指定或其他方式实现
- 用于循环的C++没有以其他方式输出
- 如何防止以 A 类以外的任何其他方式创建 B 类的对象
- 从Java调用WinMain:可能吗?任何其他方式
- 通过办公自动化或其他方式检查MS Office许可证状态
- 当使用spirit以其他方式解析结构时,会导致输出混乱
- VBOs或者其他方式
- 通过元编程或其他方式自动注册dll模块中的静态对象工厂
- 如何通过QSignalMapper或其他方式从QMenu传递QString到Qt插槽
- c++ /(MFC dummy)和纯Win MessageBox() -如何删除消息队列或以其他方式删除现有的鼠标点击/