上下文相关的模板参数推导 - type/value 参数不匹配
Context depended template argument deduction - type/value mismatch at argument
最小示例
#include <vector>
#include <tuple>
template<typename T>
void function(std::vector<T> vec)
{
auto tup = std::tuple<decltype(vec)::iterator>(vec.begin());
}
int main(int argc, char* args[])
{
std::vector<int> vec = {1,2,3};
auto tup = std::tuple<decltype(vec)::iterator>(vec.begin());
function(vec);
return 0;
}
尝试编译给出
error: type/value mismatch at argument 1 in template parameter list for ‘template<class ... _Elements> class std::tuple’
auto tup = std::tuple<decltype(vec)::iterator>(vec.begin());
^
note: expected a type, got ‘decltype (vec)::iterator’
描述的解决方案 建议添加一个 typename
。在function
中的decltype
前面加上typename
,解决了编译问题。然而:
- 为什么不能推导出类型?
- 根本问题是什么? (显然,编译器怀疑 decltype(...)::iterator 是一种类型。但为什么它在
main
中有效而在 function
中无效?)
由于iterator
是从属名,需要使用typename
关键字来消除歧义:
auto tup = std::tuple<typename decltype(vec)::iterator>(vec.begin());
// ^^^^^^^^
请注意 vec
只是 function
中的从属名称。在 main
里面它不是依赖的,所以你不需要说 typename
.
最小示例
#include <vector>
#include <tuple>
template<typename T>
void function(std::vector<T> vec)
{
auto tup = std::tuple<decltype(vec)::iterator>(vec.begin());
}
int main(int argc, char* args[])
{
std::vector<int> vec = {1,2,3};
auto tup = std::tuple<decltype(vec)::iterator>(vec.begin());
function(vec);
return 0;
}
尝试编译给出
error: type/value mismatch at argument 1 in template parameter list for ‘template<class ... _Elements> class std::tuple’
auto tup = std::tuple<decltype(vec)::iterator>(vec.begin());
^
note: expected a type, got ‘decltype (vec)::iterator’
描述的解决方案 typename
。在function
中的decltype
前面加上typename
,解决了编译问题。然而:
- 为什么不能推导出类型?
- 根本问题是什么? (显然,编译器怀疑 decltype(...)::iterator 是一种类型。但为什么它在
main
中有效而在function
中无效?)
由于iterator
是从属名,需要使用typename
关键字来消除歧义:
auto tup = std::tuple<typename decltype(vec)::iterator>(vec.begin());
// ^^^^^^^^
请注意 vec
只是 function
中的从属名称。在 main
里面它不是依赖的,所以你不需要说 typename
.