我經常使用enum類作為這樣的標志:
enum class MyFlags : uint32_t {
None = 0,
Flag1 = (1 << 0),
Flag2 = (1 << 1),
...
}
現在我經常想做這樣的組合標志的操作:MyFlags::Flag1 | MyFlags::MyFlags2
因此,我需要一個操作員過載:
MyFlags operator|(MyFlags f1, MyFlags f2)
{
return static_cast<MyFlags>(uint32_t(f1) | uint32_t(f2));
}
// other operators like =|, &, also defined.
由于我發現自己為各種enum classes
做這件事,我想為此寫一個模板,但只激活實際使用標志(opt-in)的枚舉類,所以它不用于所有枚舉。
如何為某些選定的枚舉啟用運算符?以下是我走了多遠:
// What other code here to only select this for selected types?
template <typename T> // Concept instead of typename?
T operator|(T f1, T f2)
{
return static_cast<T>(uint32_t(f1) | uint32_t(f2));
}
// Other .cpp file
// Here I'd like to do opt-in. Is this done with template specialization? std::enable_if? Other?
// What code here to use the above template for MyFlags?
正如評論中所指出的,如果可能的話,我想使用概念。如果有其他方法,那也沒關系。
因此,您可以提出您的概念:
現在的問題是如何定義您的概念,使其只滿足于您專門為其啟用的枚舉。
一種經典的方法是模板專業化:
如果您的枚舉類是在命名空間或類中定義的,則會出現一些問題,因為您必須將命名空間或類專門化。
另一種是某種標簽: