【问题标题】:Type of a class that has variadict template in another class body在另一个类主体中具有 variadict 模板的类的类型
【发布时间】:2020-10-25 16:48:07
【问题描述】:

我不是模板元编程方面的专家,我现在有点卡住了。任何帮助将不胜感激。

作为介绍。 我有一堂课(这里稍微简化了一点):

template < int dim, int spacedim, int... structdims >
class TopologyInfo
{
}

我可以使用函数创建TopologyInfo 的实例:

template < int dim, int spacedim, size_t... dims >
auto get_topology_info_imp_( std::integer_sequence< size_t, dims... > )
{
    return TopologyInfo< dim, spacedim, dims... >( );
}

template < int dim, int spacedim, int max_topo_dim_ >
auto get_topology_info( )
{
    return get_topology_info_imp_< dim, spacedim >(
      std::make_index_sequence< max_topo_dim_ >{} );
}

如果我这样使用它就可以了:

auto t = get_topology_info< 3, 3, 3 >( );

t 的类型是 TopologyInfo&lt;3, 3, 0, 1, 2&gt;,这是正确的。

那么现在的问题是:如何在不使用auto 的情况下生成t 的类型,这样我就可以将有问题的类作为另一个类的成员使用? 在我看来,我并不完全理解 std::index_sequence 背后的机制,而且解决方案应该是显而易见的。

【问题讨论】:

  • decltype(get_topology_info&lt; 3, 3, 3 &gt;( ))
  • 嗯,这确实有效。我使用decltype 来检查类型,但我从没想过我可以这样使用它。非常感谢。

标签: c++ templates variadic-templates


【解决方案1】:

auto 只是实际类型的占位符。当你写

auto t = get_topology_info< 3, 3, 3 >( );

那么t 是某种特定类型。您使用auto 的事实并没有改变这一点。

如果实际类型过于繁琐而无法拼写或不易知道,您也可以使用autos 表亲decltype。比如这个和上面的一样:

decltype( get_topology_info< 3, 3, 3>( )) t = get_topology_info< 3, 3, 3>( );

或者如果你已经有一个实例:

decltype( t ) s = get_topology_info< 3, 3, 3>( );

对于班级成员,您可能希望使用别名:

using some_meaningful_name = decltype( get_topology_info< 3, 3, 3>( ) );

然后

struct foo {
   some_meaningful_name bar;
};

【讨论】:

  • 除了using some_meaningful_name = get_topology_info&lt; 3, 3, 3&gt;( ); 之外,这有效。这仍然需要decltype( )围绕函数。
  • @szynka12 哦抱歉打错了,已修复
【解决方案2】:

只是idclev答案的延伸:

如果您在代码中重用get_topology_info 很多具有不同的值,那么您可能希望将其包装成自己的类型:

template <int A, dim, int spacedim, int max_topo_dim>
using some_meaningful_name = decltype(get_topology_info<dim, spacedim, max_topo_dim>());

所以现在我们可以说:

some_meaningful_name<3,3,3> member

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-17
    • 2019-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-28
    • 2021-08-11
    • 1970-01-01
    相关资源
    最近更新 更多