C++ 不明确的重载模板
我有以下模板代码C++ 不明确的重载模板,c++,templates,C++,Templates,我有以下模板代码 #包括 #包括 #包括 模板 void foo(标准::向量条){ 标准::cout 另一件有趣的事是: 如果未推导出非类型模板参数,则不存在强制参数和模板类型相同的限制。 template<typename T1, int SIZE> void foo(std::vector<std::array<T1, SIZE>> bar) { std::cout << "SPECIFIC (array)" << st
#包括
#包括
#包括
模板
void foo(标准::向量条){
标准::cout
另一件有趣的事是:
如果未推导出非类型模板参数,则不存在强制参数和模板类型相同的限制。
template<typename T1, int SIZE>
void foo(std::vector<std::array<T1, SIZE>> bar) {
std::cout << "SPECIFIC (array)" << std::endl;
}
int main() {
std::vector<std::array<int, 3>> b(2, std::array<int, 3> {4, 5, 6});
foo(b); // P = std::vector<std::array<int,(int)SIZE>
// A = std::vector<std::array<int,(unsigned_long)SIZE>>
// error: deduced non-type template argument does not have the same
// type as its corresponding template argument */
}
#include <vector>
#include <array>
#include <iostream>
template<typename T1, int SIZE>
void foo(std::vector<std::array<T1, SIZE>> bar) {
std::cout << "SPECIFIC (array)" << std::endl;
}
int main() {
std::vector<std::array<int, 3>> b(2, std::array<int, 3> {4, 5, 6});
foo<int,3>(b);
}
#包括
#包括我认为这仅仅是因为[temp.decrete.call]/4中的一行
通常,演绎过程试图找到模板参数值,使演绎的A与A相同
为了澄清,A
表示参数,来自[temp.decredit.call]/1
…模板参数推断,具有调用的相应参数的类型(称为A)
如前所述,将模板
更改为模板
可以解决您看到的问题。如[temp.decreate.call]/4
中所述,编译器希望推导出与A
相同的A
。因为std::array
具有模板参数
(来自[array.syn]
),它的第二个参数实际上是size\u t
,而不是int
因此,对于模板推导,您的模板的通用函数能够精确地匹配类型的A
,其中,作为您的专用模板
不是精确的匹配。我相信MSVC的推导是不正确的。FYI:您可以通过移除所有数组的外部向量
。@ChrisMM很好。这个例子是根据我的生产代码合成的,其中嵌套结构是必需的。MSVC调用数组的向量版本:@Xaser,因为数组的第二个模板参数的类型是size\u t
。考虑到R2RT的注释,似乎有编译器规范不同之处。
template<typename T1, int SIZE>
void foo(std::vector<std::array<T1, SIZE>> bar) {
std::cout << "SPECIFIC (array)" << std::endl;
}
int main() {
std::vector<std::array<int, 3>> b(2, std::array<int, 3> {4, 5, 6});
foo(b); // P = std::vector<std::array<int,(int)SIZE>
// A = std::vector<std::array<int,(unsigned_long)SIZE>>
// error: deduced non-type template argument does not have the same
// type as its corresponding template argument */
}
#include <vector>
#include <array>
#include <iostream>
template<typename T1, int SIZE>
void foo(std::vector<std::array<T1, SIZE>> bar) {
std::cout << "SPECIFIC (array)" << std::endl;
}
int main() {
std::vector<std::array<int, 3>> b(2, std::array<int, 3> {4, 5, 6});
foo<int,3>(b);
}