简体   繁体   English

如何使整数模板参数作为模板化类成员可访问?

[英]how to make integer template argument accessible as templated class member?

A common pattern with templated classes is that template argument is typedef'ed inside the class to be easily accessible: 模板化类的一种常见模式是,模板参数在类内进行了类型定义,以便于访问:

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

How can I do the same with non-type template argument? 非类型模板参数该如何做? I only had the following idea, but there gotta be something more elegant? 我只有以下想法,但是有什么更优雅的方法吗?

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

I might use an enum , but the utility of this seems somewhat limited to me... 我可能会使用一个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;
}

Edit to include that this kind of thing is frequently done in template metaprogramming. 编辑以包括在模板元编程中经常完成这种事情。

You can just use a static const variable: 您可以只使用静态const变量:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何为模板化 class 内的数据成员指定模板参数 - How to specify a template argument to a data member inside a templated class 模板化类的成员函数,以模板类型作为参数 - Member functions of a templated class, that take a template type as argument 将成员函数作为参数发送给模板化类的成员 - send a member function as an argument to a member of templated class 如何在没有参数列表的情况下将模板化 class 作为模板参数传递? - How to pass a templated class without it's argument list as a template argument? 如何在模板化类型上专门化模板类的静态成员? - How do I specialize a static member of a template class on a templated type? 模板类特化,其中模板参数是模板 - Templated class specialization where template argument is a template 非模板化类的模板成员 std::function - Template member std::function of none templated class 初始化模板类的静态模板化成员 - Initializing a static templated member of a template class 一个模板化 class 的成员 function 中的模板类型扣除 - template type deduction in a member function of a templated class 使用模板化成员函数显式实例化模板类 - Explicit instantiation of template class with templated member functions
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM