[英]non-type template parameter alias in a different type
我正在嘗試使用模板參數定義一個通用容器。 模板參數有預定義的值可供選擇。 為方便起見,我還希望允許傳遞 integer 值作為替代,並將它們自動映射到相應的預定義值。
例如(這不起作用):
struct Option {
Option(unsigned int);
};
static Option A(1);
static Option B(2);
template<Option& o>
class Value {};
Value<B> b;
Value<2> c; // <-- this is not permitted
(獎勵問題:同樣的問題,但替代值是一種類型,例如:uint8_t -> 1,uint32_t -> 2)
沒有安全或標准的方法來獲得所需的效果,如果您達到了開始看起來可行的選擇的程度,我強烈建議您重新考慮您的設計。 但是,如果你堅持,你有一個 c++17 編譯器,並且你願意使用指針而不是引用,你可以使用非類型模板參數推導,配合 SFINAE,得到想要的效果:
#include<type_traits>
struct Option{
Option(unsigned int);
}
static Option A(1);
static Option A(2);
//enable this template if the non-type template parameter is a pointer-to-Option,
// or an unsigned int can be constructed from the parameter
template<auto I, typename=std::enable_if_t<
std::is_same_v<decltype(I), Option*> ||
std::is_constructible_v<uint, decltype(I)>
>>
class Value{
};
Value<&B> b;
Value<2> c;
這將起作用,並且添加對更多類型的支持相當簡單。 但是,使用模板參數並非易事,需要一個取決於您計划如何使用模板參數的解決方案。
根據您上面的代碼,我會考慮改用枚舉類,這可能會提供更合適的替代方案:
enum class Option{
A=1,B=2
};
template<Option o>
class Value{
};
Value<Option::B> b;
Value<static_cast<Option>(2)> c;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.