c++ - 具有为实例化固定但随模板参数变化的参数数量的模板方法

标签 c++ templates

我想为带有整数模板参数的模板类定义一个函数,以便函数参数的数量取决于模板参数。这是一个例子:

template< class Coord, int dim >
class Point {
    Coord mCoords[ dim ];
public:
    void Set( /* I want exactly dim Coord arguments here. */ );
};

我希望编译这段代码:

Point<double,2> pt2d;
pt2d.Set( 25, 32 );
Point<double,3> pt3d;
pt3d.Set( 25, 32, 100 );

此代码失败:

Point<double,2> pt2d;
pt2d.Set( 25, 32, 100 );  // Too many arguments
Point<double,3> pt3d;
pt3d.Set( 25, 32 );       // Too few arguments

现在,我可以手动特化 Point在较小的尺寸中具有不相关的Set功能,但我发现基本上重复相同代码的做法不是 C++ 风格。此外,我不必专门研究 int 模板参数的每个可能值。

是否可以实现 Point<Coord,dim>::Set()恰好需要 dim 的函数Coord 类型的参数无需为 dim 的每个值编写特化代码?

最佳答案

您可以使用 Boost.Hana 用于 getNth 的技巧:

template <typename Coord, int dim, typename = std::make_index_sequence<dim>>
struct Point;

template <typename Coord, int dim, size_t... Ignore>
struct Point<Coord, dim, std::index_sequence<Ignore...>>
{
    void Set(decltype(Ignore, Coord{})... args)
    {
        // ...
    }
};

一个更长的版本隐藏了一点Ignore的丑陋(并且适用于非默认构造的Coords ...)将添加一些元编程样板:

template <typename... > struct typelist { };

template <int N, typename T, typename = std::make_index_sequence<N>>
struct repeat;

template <int N, typename T>
using repeat_t = typename repeat<N, T>::type;

template <int N, typename T, size_t... Idx>
struct repeat<N, T, std::index_sequence<Idx...>>
{
    template <size_t >
    struct makeT { using type = T; };

    using type = typelist<typename makeT<Idx>::type...>;
};

然后专注于repeat_t。并将它隐藏在命名空间中,这样用户就不会搞砸了:

namespace details {
    template <typename Coord, int dim, typename = repeat_t<dim, Coord>>
    struct Point;

    template <typename Coord, int dim, typename... dimCoords>
    struct Point<Coord, dim, typelist<dimCoords...>>
    {
        void Set(dimCoords... args)
        {

        }
    };
}

template <typename Coord, int dim>
using Point = details::Point<Coord, dim>;

关于c++ - 具有为实例化固定但随模板参数变化的参数数量的模板方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32913055/

相关文章:

c++ - OpenCL copyto() 消耗更多时间

c++ - 高级 C 或 C++ 书籍

c++ - 模板模板总特化

c++ - 在没有锁的情况下创建 thread_safe shared_ptr 的正确方法?

c++ - 如何防止我的程序打印额外的斜杠?

c++ - 避免采用 int 参数的模板类的 C++ 爆炸式实例化

c++ - variadic template template中的Variadic template推导

node.js - Nunjucks: 'if' 与多个 'and' 或 'or' 条件

c++ - 无法理解复制构造函数从何而来

C++ 安全 boolean 包装器