c++ - 是否允许多个非类型模板参数包?

标签 c++ templates c++11 language-lawyer

[temp.param] p11 说(在 N4527 中):

(...) A template parameter pack of a function template shall not be followed by another template parameter unless that template parameter can be deduced from the parameter-type-list of the function template or has a default argument

非类型模板参数包的上下文中,不能有默认参数,
那么究竟需要为包推导出什么(只是类型,还是值)?

即我想知道标准(C++11、14 或 1z)是否允许这样做:

template<typename T, T... A, T... B>
void foo(T) {}

第一个包的值可以明确指定,但第二个包是“无法访问的”,如果我没记错的话,它总是空的。

clang++-3.6 和 g++-5.2 似乎接受这些空的无法访问的包(甚至是非非类型包),但 VC++ 14.0 拒绝它们并出现错误:

error C3547: template parameter 'B' cannot be used because it follows a template parameter pack and cannot be deduced from the function parameters of 'foo'

最佳答案

不,标准不允许。来自 [temp.param]:

A template parameter pack of a function template shall not be followed by another template parameter unless that template parameter can be deduced from the parameter-type-list of the function template or has a default argument (14.8.2). [Example:

template<class T1 = int, class T2> class B;    // error

// U can be neither deduced from the parameter-type-list nor specified
template<class... T, class... U> void f() { }  // error
template<class... T, class U> void g() { }     // error

—end example ]

在你的情况下, ...B 不能被推导出来(因为没有任何东西可以推导出来)并且它没有默认参数。

so what exactly needs to be deduced for the packs (just the type, or the values, too)?

例如,如果您的 foo 是:

template <size_t... A, size_t... B>
void foo(std::index_sequence<B...> );

...A 后跟 ...B,但是可以推导出 ...B,所以这是允许的。同样:

template <typename T, T... A, T B = 0>
void foo();

很好,因为 B 有一个默认参数。

关于c++ - 是否允许多个非类型模板参数包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31697055/

相关文章:

c++ - 等价于 C 中的 std::aligned_storage<>?

templates - 如何将可选的 Facelet 模板内容包装在 div 标签中?

c++ - 模板 : one for string and one for anything else 中的不同构造函数

c++ - 如何从 unique_ptr<Base> 的 vector 中获取派生迭代器?

C++线程开销

c++ - LLVM 运行 PassManager(非遗留)

c++ - 按字典顺序比较字符串

c++ - 为什么 Visual Studio Community 2022 编译我的 C++ 代码?

c++ - 如何在C++中将不同模板类型的对象相乘

c++ - 在类中存储 Lambda