目前使用 C 20、GCC 11.1.0。
我正在嘗試在具有唯一性的命名空間中創建型別value和name. 我專門想出了這個結構,以便能夠使用范圍決議運算子訪問變數,如下所示foo::bar::name:但是,我不知道如何初始化name變數。我嘗試添加第二個非型別引數const char* barName,但它不允許我使用字串文字作為模板引數。
代碼:
namespace foo
{
template<uint32_t id>
struct bar
{
static constexpr uint32_t value {id};
static constexpr std::string_view name {};
};
using a = bar<0>;
using b = bar<1>;
}
錯誤代碼:
namespace foo
{
template<uint32_t id, const char* barName>
struct bar
{
static constexpr uint32_t value {id};
static constexpr std::string_view name {barName};
};
using a = bar<0, "a">;
using b = bar<1, "b">;
}
uj5u.com熱心網友回復:
由于我們不能將字串文字作為模板引數傳遞,我們必須使用其他方式。特別是,我們可以有一個靜態const char陣列變數,如下所示:
static constexpr char ch1[] = "somestrnig";
static constexpr char ch2[] = "anotherstring";
namespace foo
{ //--------------------vvvvvvvvvvvvvvvv--->added this 2nd template parameter
template<uint32_t id, const char* ptr>
struct bar
{
static constexpr uint32_t value {id};
//--------------------------------------vvvv-->added this
static constexpr std::string_view name {ptr};
};
//---------------vvv----->added this
using a = bar<0, ch1>;
using b = bar<1, ch2>;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/511318.html
標籤:C 模板
