I have a (container like) class that accepts several of my other types/classes as the data member. Now I would like to specify some properties (edit: positive integer) of the data type as compile time information. This works fine, but I would like to static_assert
that the provided type is correct (uint8_t), the actual value is different for most data type classes. I set the number as a std::integral_constant
with uint8_t
.
1) How do I do that (see example code provided)?
2) Is there a better approach?
I can use language features up to c++17.
( edited for clarification )
class DataClass
{
public:
// compile time information about char count
using char_count = std::integral_constant<uint8_t, 2>;
private:
...
}
class DataClass2
{
public:
// compile time information about char count
using char_count = std::integral_constant<uint8_t, 4>;
private:
...
}
template <typename DataType, ...>
class ContainerClass
{
private:
// does not work: error C2923: 'std::is_same_v':
// 'value' is not a valid template type argument for parameter '<unnamed-symbol>'
static_assert(std::is_same_v<DataType::char_count::value, uint8_t>, "not uint8_t");
// this also does not work
static_assert(std::is_same_v<decltype(DataType::char_count::value), uint8_t>, "also not uint8_t");
// using the value actually works fine
constexpr static auto char_count = DataType::char_count::value;
public:
...
}
What you want to do depends on what exatly do you want to check.
char_count
has value 2? static_assert(DataType::char_count::value == 2, "char_count is not 2;");
char_count
is an integral constant (or something else) that has uint8_t
as type
member type alias? static_assert(std::is_same_v(typename DataType::char_count::value_type, "char_count is not uint8_t;");
char_count
is an integral constant with value 2 and type uint8_t
? static_assert(std::is_same_v<DataType::char_count, std::integral_constant<uint8_t, 2>>, "char_count is not 2 or not uint8_t;");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.