c++ - C++ 是否允许在可变参数模板参数之后使用普通参数?

标签 c++ c++11 templates standards variadic-templates

根据 cppreference ,下面的代码是合法的:

lock_guard( MutexTypes&... m, std::adopt_lock_t t );

但是,以下代码不能用 clang 3.8 (-std=c++1z) 编译:

template<typename... Args>
void f(Args&&..., bool)
{}

int main()
{
    f(1, 2, 3, true); // error! see below for details.
}
1>main.cpp(59,2): error : no matching function for call to 'f'
1>          f(1, 2, 3, true);
1>          ^
1>  main.cpp(54,6) :  note: candidate function not viable: requires 1 argument, but 4 were provided
1>  void f(Args&&..., bool)
1>       ^
1>  1 error generated.

C++ 是否允许在可变参数之后使用普通参数?

最佳答案

您的代码中的函数声明是有效的,但是推导对于此类函数模板无法正常工作。请注意,以下代码格式正确,并实例化了特化 void f(int, int, int, bool):

template<typename... Args>
void f(Args&&..., bool) {}

int main() {
    f<int, int, int>(1, 2, 3, true);
}

请注意,在 C++17 中,MutexTypes... 是类本身的模板参数:

template <class... MutexTypes> class lock_guard;

因此它们是已知的,不需要推导。请注意,带有 adopt_lock_t 的构造函数不能用于 C++17 类模板参数推导,因为 adopt_lock_t 参数出现在参数包之后。如果委员会在 C++11 中有先见之明,他们会把 adopt_lock_t 参数放在开头而不是结尾,但遗憾的是,现在为时已晚。

关于c++ - C++ 是否允许在可变参数模板参数之后使用普通参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42269453/

相关文章:

c++ - 如何立即取消 curl 操作?

c++ - 在 C++11 中如何使用 std::async with std::launch::any

c++ - 为 SFINAE 测试仪提供默认值零的原因是什么?

c++ - 如何在适当的时候让模板函数在插入器上使用 back_inserter

c++ - 最简单的template-template为什么编译不出来?

javascript - 如何使用 CSS3 animate 上下移动 div 的背景图像?

c++ - 使用 pthread_win32 增加进程优先级

c++ - 将基于模板的私有(private)实现桥接到非模板化公共(public) API

c++ - 指向派生类成员函数的指针,但不是派生(虚拟)函数

c++ - 创建从一种类型到另一种类型的别名