C++17中如何在std::conditional_t中使用void类型
问题解决:基于std::conditional_t正确定义std::function成员类型
问题根源
当N==1时,你通过std::conditional_t得到的index_t是void,此时std::function<T(index_t)>会被编译器解析为接受一个void类型参数的函数包装,但C++不允许void作为函数参数的具体类型(仅能在函数声明中用()或(void)表示无参数),因此触发编译错误。
解决方案
直接用std::conditional_t选择完整的std::function类型,而非仅选择参数类型。这样可以在N==1时得到std::function<T()>(无参数的函数包装),N>1时得到std::function<T(uint32_t)>(接受uint32_t参数的函数包装)。
修正后的代码
#include <functional> #include <stdexcept> #include <cstdint> template <class T, size_t N = 1> class MyClass { static_assert(N > 0, "0 or less feature element isn't allowed"); public: // 直接选择完整的std::function类型 using function_type = std::conditional_t<N == 1, std::function<T()>, std::function<T(uint32_t)>>; private: function_type fRead; public: template <typename U = T> std::enable_if_t<N == 1, U> getData() { return fRead(); } template <typename U = T> std::enable_if_t<N > 1, U> getData(uint32_t index) { if (index >= N) { throw std::out_of_range("Index is out of range!"); } return fRead(index); } }; // 补上类定义的分号
补充说明
- 去掉了原代码中不必要的
index_t定义,直接通过function_type指定fRead的类型,更直观且避免参数类型歧义。 - 确保类定义末尾添加分号,符合C++语法要求。
- 当
N==1时,fRead是std::function<T()>,调用fRead()符合无参数函数的调用语法;当N>1时,fRead是std::function<T(uint32_t)>,调用fRead(index)完全匹配参数类型。
内容的提问来源于stack exchange,提问作者moudi
相关产品推荐
相关产品推荐

