簡體   English   中英

如何使整數模板參數作為模板化類成員可訪問?

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

模板化類的一種常見模式是,模板參數在類內進行了類型定義,以便於訪問:

#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");

我可能會使用一個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;
}

編輯以包括在模板元編程中經常完成這種事情。

您可以只使用靜態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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM