首页 > 解决方案 > 为什么这段代码抱怨“非类型模板参数不能有类型”?

问题描述

编码:

#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>(注意大括号初始化{})。

我也不确定第二个错误,但我稍后会解决。

标签: c++templatesc++14variadic-templates

解决方案


您正在尝试对模板参数 ( cppreferencestd::greater<T> )不可接受的类型进行参数化:

  • std::nullptr_t(C++11 起)
  • 整型(注:bool为整型)
  • 左值引用类型(对象或函数);
  • 指针类型(指向对象或函数);
  • 指向成员类型的指针(指向成员对象或成员函数);
  • 枚举类型。

推荐阅读