首页 > 解决方案 > 依赖于未知 typedef 的模板特化

问题描述

在 C++ 中,我想专门化一个模板化函数。到现在为止还挺好。
问题是专门化我的模板的类型取决于我无权访问的 typedef。

目的说明

Surface_mesh用户必须首先通过在模板中指定一些类型来为该类定义一个 typedef 。

typedef CGAL::Surface_mesh<CGAL::Simple_cartesian<double>::Point_3> Mesh;

Mesh可能会根据用户的需要而有所不同,但它始终具有以下 typedef:

现在我想编写一个函数,该函数具有不同的实现Face_index,取决于 typedefVertex_indexEdge_index但不取决于 typedef Mesh。以下是用户如何使用它:

std::cout << foo<void>() << std::endl;
std::cout << foo<Mesh::Face_index>() << std::endl;
std::cout << foo<Mesh::Vertex_index>() << std::endl;
std::cout << foo<Mesh::Edge_index>() << std::endl;

>> "Default foo() called"
>> "foo() for Face_index called"
>> "foo() for Vertex_index called"
>> "foo() for Edge_index called"

我试过的

如果foo可以访问Meshtyedef,则第一个实现工作,但情况并非如此:

template <typename EI> //for Element Index
std::string foo(void)
{
    return "Default foo() called";
}

template <>
std::string foo<Mesh::Face_index>(void)
{
    return "foo() for Face_index called";
}

...

所以我尝试了类似的方法,但它不起作用:

template <typename SM, typename EI> //for Surface Mesh and Element Index
std::string foo(void)
{
    return "Default foo() called";
}

template <typename SM>
std::string foo<SM::Face_index>(void)
{
    return "foo() for Face_index called";
}

...

问题

你知道是否可以做我想做的事,如果可以的话怎么做,或者你有链接到网站的解释可以帮助我吗?


编辑

这是 Surface_Mesh 的简化实现:

namespace CGAL
{
    // Implementation for Surface_mesh::Vertex_index
    class SM_Vertex_index
    {
        //...
    };

    // Implementation of Surfae_mesh::Face_index
    class SM_Face_index
    {
        //...
    };

    template <typename P>
    class Surface_mesh
    {
    public:
        typedef SM_Vertex_index Vertex_index;
        typedef SM_Face_index Face_index;
        //... (P is used in the code)
    };
}

标签: c++templates

解决方案


在 CGALFace_index中 - 除了创建文档的情况外 - 只是一个typedeffor SM_Face_idex( typedef SM_Face_index Face_index;) 并且对于所有表面网格都是相同的。

所以理论上你可以这样做:

template <typename T>
std::string foo(void)
{
    return "Default foo() called";
}

template <>
std::string foo<SM_Face_index>(void)
{
    return "foo() for Face_index called";
}

这适用于当前的 CGAL 版本,但我在文档中看不到任何内容,这将保证在未来是这样的。

问题在于文档声称它Face_index是在 Mesh 中定义的实际类,而不是typedef独立于表面网格的类型。


推荐阅读