为了简化我的问题,我将使用 std::unique_lock
作为解释的工具。
std::unique_lock 有一个模板参数,互斥锁。但是,它的构造函数也是一个模板函数 unique_lock(TMutex &, const chrono::duration<_Rep, _Period>&)
.
当一个人使用它时,可以这样写:
auto lock = std::unique_lock(my_mutex, 5s);
那么,问题是:如何为此(不改变行为)写出推导指南,怎么做?
到目前为止我最好的尝试:
template<typename _Mutex>
template<typename _Rep, typename _Period>
unique_lock(_Mutex &, const chrono::duration<_Rep, _Period>&) -> unique_lock<_Mutex>;
不幸的是,clang 不接受这个:
error: extraneous template parameter list in template specialization or out-of-line template definition
最佳答案
GCC 对此有更好的错误消息:
error: too many template-parameter-lists
您可以将其更改为单个模板参数列表,如下所示:
template<typename _Mutex, typename _Rep, typename _Period>
unique_lock(_Mutex &, const chrono::duration<_Rep, _Period>&) -> unique_lock<_Mutex>;
而且它有效。
从您问题中的评论来看,您似乎在混合使用 CTAD 和特化。
您没有专门研究 unique_lock
中的任何内容。不是成员函数,也不是构造函数,你只是在定义一个推导指南。
更具体地说,来自 cppreference :
The syntax of a user-defined deduction guide is the syntax of a function declaration with a trailing return type [...] A deduction guide is not a function [...]
请注意,它具有声明语法,而不是特化语法。只是与您的预期不同。
关于c++ - 如何使用模板化构造函数定义推导指南?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57349940/