gpt4 book ai didi

c++ - 实例化函数模板时省略模板类型参数是否合法?

转载 作者:行者123 更新时间:2023-12-01 21:43:29 27 4
gpt4 key购买 nike

以下代码实现了一个函数模板 foo,它接受任意数量的参数,并随后处理每个参数,同时维护该参数的位置索引:

template<int index, typename T>
void foo_impl(T value)
{
// Do something with index/value
}

template<int index, typename T, typename... Rest>
void foo_impl(T value, Rest... values)
{
// Do something with index/value
// Recursively handle remaining arguments
foo_impl<index + 1>(values...);
}

template<typename... T>
void foo(T... args)
{
foo_impl<1>(args...);
}

int main()
{
foo("test", 42);
}

这会递归地实例化函数模板,直到到达采用单个参数的基本模板。 foo_impl 的每个函数模板实例化都会忽略模板类型参数。虽然这个compiles with Clang, GCC, and MSVC ,我不确定这是否合法。

如代码示例所示省略模板参数是否合法?如果有,具体规则是什么?这些规则在 C++ 标准之间是否发生了变化?

最佳答案

具体规则在[temp.arg.explicit]

3 Trailing template arguments that can be deduced or obtained from default template-arguments may be omitted from the list of explicit template-arguments. A trailing template parameter pack not otherwise deduced will be deduced to an empty sequence of template arguments. If all of the template arguments can be deduced, they may all be omitted; in this case, the empty template argument list <> itself may also be omitted. In contexts where deduction is done and fails, or in contexts where deduction is not done, if a template argument list is specified and it, along with any default template arguments, identifies a single function template specialization, then the template-id is an lvalue for the function template specialization.

由于类型参数是尾随的,并且可以从函数调用的参数中推导出来,因此可以省略它们。

迄今为止的所有标准修订版中都存在此类措辞(除了有关参数包的部分,C++03 中不存在这些内容)。

关于c++ - 实例化函数模板时省略模板类型参数是否合法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60603868/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com