【问题标题】:how to make integer template argument accessible as templated class member?如何使整数模板参数可作为模板类成员访问?
【发布时间】:2012-05-12 20:33:31
【问题描述】:

模板化类的一个常见模式是模板参数在类内部进行了类型定义,以便于访问:

#include <type_traits>
template<class T> struct Foo{
    typedef T type;
};
static_assert(std::is_same<Foo<int>::type,int>::value,"");

我怎样才能对非类型模板参数做同样的事情?我只有以下的想法,但一定有更优雅的东西吗?

template<int I> struct Bar{
   constexpr static int getI(){ return I; }
};
static_assert(Bar<5>::getI()==5,"error");

【问题讨论】:

  • 为什么不优雅?
  • 这是一个方法调用;为什么这是个问题?
  • 这不是一个“正常”的方法调用,而是一个constexpr,一个在编译时解析的表达式。出于这个原因,如果可能的话,我更喜欢它看起来不同。

标签: c++ templates


【解决方案1】:

我可能会使用enum,但它的实用性似乎对我来说有点有限......

#include <iostream>
using namespace std;

template<int N> struct Foo
{
    enum {value_ = N};
};

int main(int argc, char* argv[])
{            
    Foo<42> foo;

    cout << foo.value_;

    return 0;
}

编辑以包括这种事情在模板元编程中经常完成。

【讨论】:

  • 酷!正是我需要的。如果模板作为参数传递给另一个可能想要查询该参数的函数,这将非常有用;除非以这种方式“保存”在某处,否则无法访问。
  • 考虑例如std::tuple_size。我认为这是非常不雅的。 std::tuple&lt;...&gt;::size 会更具可读性。
【解决方案2】:

你可以只使用一个静态常量变量:

template<int I> struct Bar{
    static const int i = I;
};

static_assert(Bar<5>::i==5,"error");

【讨论】:

  • 你必须记住在某个地方定义它,这很烦人。
  • 对,因此我没有提出这个建议。它编译文件,然后在链接时出现错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-06
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
相关资源
最近更新 更多