c++ - 模板推导指南中的附加类型

标签 c++ c++17 template-argument-deduction

此代码片段演示了如何使用推导指南来允许 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/

相关文章:

c++ - 静态对象实例必须有静态成员变量吗?

c++ - 无法将任何文件添加到 GIT "libgit2 returned: Invalid data in index - invalid entry"

c++ - 检查类是否是模板专用化(使用 bool 或 int 等模板参数)

c++ - 有没有办法在 C++17 中创建编译时类型映射以进行类型检查?

c++ - 传递可变参数 std::function

C++11模板解析错误,使用模板别名进行类型推导

c++ - 获取当前聚焦窗口的可执行名称?

c++ - 了解内存序列和 std::memory_order_relaxed

c++ - 模板的自动返回类型和歧义

c++ - 我可以跨 DLL 边界传递 FILE 对象吗?