此代码片段演示了如何使用推导指南来允许 source_location::current
与参数包一起使用(请参阅 https://stackoverflow.com/a/57548488/1421332 ):
template <typename... Params>
struct Test
{
Test(Params&&... params,
const std::source_location& loc = std::source_location::current());
};
template <typename ...Params>
Test(Params&&...) -> Test<Params...>;
使用方式如下:
Test(5, 'A', 3.14f, "foo");
现在我想通过应明确指定的附加类型 T 来扩展结构 Test。我尝试了以下方法,但推演指南不被接受:
template <typename T, typename... Params>
struct Test
{
Test(Params&&... params,
const std::source_location& loc = std::source_location::current());
};
template <typename T, typename ...Params>
Test(Params&&...) -> Test<T, Params...>;
编译器说:
deduction guide template contains a template parameter that cannot be deduced.
我需要额外的 T 来允许 struct Test 内部构建用户指定类型的对象。
应该这样使用:
Test<MyType>(5, 'A', 3.14f, "foo");
是否可以定义包含附加T的扣除指南?
最佳答案
你不能用这种语法来做到这一点:
Test<MyType>(5, 'A', 3.14f, "foo");
因为不存在“部分”类模板参数推导之类的东西。要么全有,要么全无 - 您要么指定所有类模板参数,要么不指定类模板参数。
但是,您可以将类型移过去:
template <typename T> struct type_t {};
template <typename T> inline type_t<T> type{};
Test(type<MyType>, 5, 'A', 3.14f, "foo");
现在您已经推导出类型了。您甚至可以编写推导指南来要求这种用法:
template <typename T, typename ...Params>
Test(type_t<T>, Params&&...) -> Test<T, Params...>;
虽然Test
的构造函数仍然需要采用 type_t<T>
先论证。
关于c++ - 模板推导指南中的附加类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58492439/