我想使用整数模板参数为模板类定义一个函数,以便函数参数的数量取决于模板参数.这是一个例子:
template< class Coord, int dim >
class Point {
Coord mCoords[ dim ];
public:
void Set( /* I want exactly dim Coord arguments here. */ );
};
Run Code Online (Sandbox Code Playgroud)
我想要编译这段代码:
Point<double,2> pt2d;
pt2d.Set( 25, 32 );
Point<double,3> pt3d;
pt3d.Set( 25, 32, 100 );
Run Code Online (Sandbox Code Playgroud)
并且此代码失败:
Point<double,2> pt2d;
pt2d.Set( 25, 32, 100 ); // Too many arguments
Point<double,3> pt3d;
pt3d.Set( 25, 32 ); // Too few arguments
Run Code Online (Sandbox Code Playgroud)
现在,我可以手动专注Point于较小的维度以具有不相关的Set功能,但我发现基本上重复相同的代码un-C++的做法 - ish.此外,我不应该专门针对int模板参数的每个可能值.
有没有可能实现的Point<Coord,dim>::Set()函数可以采用完全dim类型的参数而Coord无需为每个值编写特化代码dim?
Bar*_*rry 10
您可以使用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)
{
// ...
}
};
Run Code Online (Sandbox Code Playgroud)
Ignore一个稍微隐藏丑陋的较长版本(适用于非默认可构造Coord的...)将添加一些元编程样板:
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...>;
};
Run Code Online (Sandbox Code Playgroud)
然后专注于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>;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
188 次 |
| 最近记录: |