我想对 MyClass 使用 std::enable_if 以便仅接受 (uint32_t | uint64_t) 并且同时如果用户未提供任何类型;根据以下条件选择默认值。
但我无法让它工作。 (C++17)
#include <vector>
#include <cstdint>
template <typename T=std::conditional_t<sizeof(void*) == 8, std::uint64_t, std::uint32_t>>
class MyClass
{
private:
std::vector<T> vs;
public:
// ...
};
int main(){
MyClass a; // OK, the defaut type is used either uint32_t or uint64_t
MyClass<std::uint32_t> b; // Ok, use the user provided type
MyClass<long> c; // must not compile, T is not one of uint32_t, uint64_t
}
最佳答案
您可以添加static_assert
执行检查。
template <typename T=std::conditional_t<sizeof(void*) == 8, std::uint64_t, std::uint32_t>>
class MyClass
{
static_assert(std::is_same_v<T, std::uint64_t> || std::is_same_v<T, std::uint32_t>, "T must be std::uint64_t or std::uint32_t");
private:
std::vector<T> vs;
public:
// ...
};
关于c++ - 模板类默认类型和条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59703844/