C++如何用模板特化或其他方式实现?

C++ how to implement with template specilization or other manner?

我正在实现边界卷层次结构,其中树具有如下模板:

template <typename Coordinate> 
class BoundingTree { /* ... */ }

Coordinate可以是Vector2dVector3f或其他任意坐标。要使用这个BoundingTree结构进行碰撞检测,应该有一个检测函数:

template <typename Coordinate> 
template <typename RigidBody>
bool BoundingTree::collide(RigidBody const & body);

RigidBody 可以是一切,例如Cuboid3fCircle2d。而我对这个检测系统的实现是:

// 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'

如何解决这个问题?

有没有更好的方法来实现这个任意类型的碰撞检测系统?

非常感谢。

您正在尝试做什么 is allowed 但您有一个语法错误:

template<typename Coordinate> template <typename RigidBody>
bool BoundingTree::collide(RigidBody const & obj)
                         ^

这不是专业化,因此您必须为 class 指定模板参数,它应该是

bool BoundingTree::collide<Coordinate>(...)

但我看到您的代码分为 header 和源代码,这可能会造成代码非专业化的问题。

如果模板化函数在源文件中定义但在另一个翻译单元中使用,则在编译期间不会生成模板的实例化,您将遇到链接器错误。

完全专业化不会发生这种情况,例如

template<> template<>
bool BoundingTree<Vector3f>::collide<Sphere3f>(Sphere3f const & d)

但是如果您计划进行部分特化,那么您将被迫移动 header 文件中的所有内容,或者强制在定义它们的源文件中实例化模板,例如

template class BoundingTree<MyCoord>;
template bool BoundingTree<MyCoord>::collide<MyShape>(MyShape const& d);