我正在嘗試重構“std::filesystem::path path = blah; if (path.extension() == ".whatever") load_file(path) else abort/error”的整個代碼庫。
到目前為止,我已經將我的列舉撰寫為一個位域,其中包含我希望我的應用程式接受的所有檔案擴展名,以及 Assets 命名空間中的這個函式:
enum class AcceptedFileExtension : uint32_t {
SCENE = BIT(0),
OBJ = BIT(1),
GLTF = BIT(2),
GLB = BIT(3),
PNG = BIT(4),
JPG = BIT(5),
TTF = BIT(6),
VERT = BIT(7),
FRAG = BIT(8),
SPV = BIT(9),
};
template <AcceptedFileExtension T>
static std::optional<std::filesystem::path> accept(const std::filesystem::path& path)
{
if (to_accepted_extension(path) == T) {
return { path };
}
return {};
}
其中模板型別是我的列舉,本質上定義為位域(每個成員 = 1 << n,例如 AcceptedFileExtension::PNG = 1 << 3)。
我希望這個函式接受邏輯上的“或”-d 值作為模板,例如:
// AFE = AcceptedFileExtension
auto path_or_nothing = Assets::accept<AFE::PNG | AFE::JPG>(assets_folder_path / images);
I recently read this post on SO and tried to write my own implementation for a new API, which added the logical operators to the enum class I'd written. However, the problem is obvious, this creates a value (?) and not a type which I can use in templates. These are inline constexpr, and implements or, and, xor.
If I then make the enum class into a parameter for the function as an R-value (which is how the caller should use it), another issue arises:
static std::optional<std::filesystem::path> accept(const std::filesystem::path& path, AcceptedFileExtension&& afe)
{
// Does not compile, since "&" does not reduce this to bool but to AFE.
if (to_accepted_extension(path) & afe) {
return { path };
}
return {};
}
How do I move forward?
Thank you.
uj5u.com熱心網友回復:
operator|您可以為您的列舉撰寫自己的多載。例如
#include<cstdint>
constexpr uint32_t BIT(int i){
return static_cast<uint32_t>(1)<<i;
}
enum class AcceptedFileExtension : uint32_t {
SCENE = BIT(0),
OBJ = BIT(1),
GLTF = BIT(2),
GLB = BIT(3),
PNG = BIT(4),
JPG = BIT(5),
TTF = BIT(6),
VERT = BIT(7),
FRAG = BIT(8),
SPV = BIT(9),
};
constexpr AcceptedFileExtension operator|(
AcceptedFileExtension const& lhs,
AcceptedFileExtension const& rhs
){
return static_cast<AcceptedFileExtension>(
static_cast<uint32_t>(lhs) |
static_cast<uint32_t>(rhs)
);
}
template <AcceptedFileExtension T>
static void accept()
{
}
int main(){
accept<AcceptedFileExtension::PNG | AcceptedFileExtension::JPG>();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/444268.html
標籤:c enums bit-fields
上一篇:將臨時系結到r值參考會產生錯誤
下一篇:回傳值時布爾檢查行為例外
