[英]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.