c++ - 为什么这段代码抱怨“非类型模板参数不能有类型”?
问题描述
编码:
#include <functional>
#include <type_traits>
namespace impl
{
// lame recursive implementation
template<typename Functor, Functor F, typename T, T OneValue, T SecondValue, T... Values>
struct variadic_conjunction : variadic_conjunction<Functor, F, T, F(OneValue, SecondValue), Values...> {};
template<typename Functor, Functor F, typename T, T OneValue, T SecondValue>
struct variadic_conjunction<Functor, F, T, OneValue, SecondValue> : std::integral_constant<T, F(OneValue, SecondValue)> {};
}
template<typename Functor, Functor F, typename T, T... Values>
struct variadic_conjunction : impl::variadic_conjunction<Functor, F, T, Values...> {};
template<typename Functor, Functor F, typename T, T... Values>
constexpr T variadic_conjunction_v = variadic_conjunction<Functor, F, T, Values...>::value;
template<typename T, T... Values>
struct variadic_max : variadic_conjunction<std::greater<T>, std::greater<T>{}, T, Values...> {};
template<typename T, T... Values>
constexpr T variadic_max_v = variadic_max<T, Values...>::value;
int main()
{
constexpr auto max = variadic_max_v<std::size_t, 4, 8>;
}
您可以在 coliru 上使用它:http: //coliru.stacked-crooked.com/a/17c5065229594de9。
它抱怨这个:
main.cpp:14:36: error: a non-type template parameter cannot have type 'std::__1::greater<unsigned long>'
template<typename Functor, Functor F, typename T, T... Values>
^
main.cpp:21:23: note: while substituting prior template arguments into non-type template parameter 'F' [with Functor = std::__1::greater<unsigned long>]
struct variadic_max : variadic_conjunction<std::greater<T>, std::greater<T>{}, T, Values...> {};
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
main.cpp:24:30: note: in instantiation of template class 'variadic_max<unsigned long, 4, 8>' requested here
constexpr T variadic_max_v = variadic_max<T, Values...>::value;
^
main.cpp:28:26: note: in instantiation of variable template specialization 'variadic_max_v<unsigned long, 4, 8>' requested here
constexpr auto max = variadic_max_v<std::size_t, 4, 8>;
^
main.cpp:28:26: error: constexpr variable 'max' must be initialized by a constant expression
constexpr auto max = variadic_max_v<std::size_t, 4, 8>;
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2 errors generated.
但据我所知,我正在传递一个实例std::greater<T>
(注意大括号初始化{}
)。
我也不确定第二个错误,但我稍后会解决。
解决方案
您正在尝试对模板参数 ( cppreferencestd::greater<T>
)不可接受的类型进行参数化:
std::nullptr_t
(C++11 起)- 整型(注:
bool
为整型) - 左值引用类型(对象或函数);
- 指针类型(指向对象或函数);
- 指向成员类型的指针(指向成员对象或成员函数);
- 枚举类型。
推荐阅读
- kotlin - let 函数如何保证值不会为空?
- excel - 格式化部分单元格
- javascript - 如何使用 replace() 仅去除非重音字符
- android - Viewpager 在调用隐含意图后从当前页面移动到默认片段页面
- random - tasks.json 中的预定义变量返回 GUID
- git - 子模块 - 更新 .gitmodules 以指定分支名称
- r - R直接从数据中绘制置信区间,无需计算
- vue.js - 通过将插槽更改为作用域插槽,它不再出现在 this.$slots 和 this.$scopedslots
- pip - 错误:torch 的轮子无效,.dist-info 目录未找到
- javascript - 类型 '{ [key: string]: AbstractControl; }' 必须有一个返回迭代器的 '[Symbol.iterator]()' 方法