Jef*_*f G 5 c++ templates g++ c++14
我正在尝试使用 C++ 模板创建与 Visual Studio _countof 宏等效的内容。以下是我建议的定义:
\n\ntemplate<typename T, size_t N>\ninline constexpr size_t countof(T const (&array)[N]) {\n return N;\n}\ntemplate<typename T, typename U, size_t N>\ninline constexpr size_t countof(T const (U::&array)[N]) {\n return N;\n}\nRun Code Online (Sandbox Code Playgroud)\n\n上面的第二个声明是尝试修复以下代码,该代码在 g++ 9 中生成编译时错误,并显示消息:“错误:无效使用非静态数据成员 \xe2\x80\x98foo::bar\xe2\ x80\x99":
\n\nstruct foo {\n int const bar[4];\n static_assert(countof(bar) == 4);\n};\nRun Code Online (Sandbox Code Playgroud)\n\n但是,当我添加第二个定义并将断言更改为 use 时foo::bar,g++ 生成错误:“错误:\xe2\x80\x98template constexpr const size_t countof\xe2\x80\x99 与先前的声明冲突”。
我可以更改代码以使用指向成员的指针(而不是对成员的引用),但这似乎是不必要的。有谁知道一种方法来制作countof仅在传递数组时才编译的版本,并且以合理的方式适用于自由数组和成员变量数组?
问题是 的用法bar在 中无效static_assert(countof(bar) == 4);,您需要一个 的实例并获取要传递给 的foo成员数组。barcountof
我可以更改代码以使用指向成员的指针(而不是对成员的引用),但这似乎是不必要的。
您可以更改代码以使用指向成员的指针。例如
template<typename T, typename U, size_t N>
inline constexpr size_t countof(T const (U::*array)[N]) {
return N;
}
Run Code Online (Sandbox Code Playgroud)
然后
static_assert(countof(&foo::bar) == 4);
Run Code Online (Sandbox Code Playgroud)
或者更改countof为指定类型,而不是将数组传递给它。
template<typename T>
struct count_of{};
template<typename T, size_t N>
struct count_of<T const [N]> {
constexpr static size_t value = N;
};
template<typename T>
inline constexpr size_t countof() {
return count_of<T>::value;
}
Run Code Online (Sandbox Code Playgroud)
然后
static_assert(countof<decltype(foo::bar)>() == 4);
Run Code Online (Sandbox Code Playgroud)