考虑:
#include <vector>
template<int N> class B {};
template<int N> class A {};
template<int N, template<int> class T>
void doSomething(T<N> const& my_type) {
//do sth...
}
int main() {
B<42> b;
doSomething(b); //OK
std::vector<A<43>> vec_a;
doSomething(vec_a); //FAIL: "no matching function for call to 'doSomething'
// "candidate template ignored: could not match N against 'A<43>'"
return 0;
}
我知道编译器不是将 N 与 43 绑定(bind),而是尝试将其与 A<43> 绑定(bind)(这是有道理的,因为 vec_a 的类型是 std::vector<A<43>>
而不是 std::vector<A><43>
或类似的类型)并且逻辑上没有这样做。
我该怎么办? (编译器:clang++ 3.3)
最佳答案
您可以添加第二个接受 vector 的重载:
#include <vector>
template <typename T, typename A>
void doSomething(std::vector<T, A> const & v)
{
doSomething(v[3]);
};
正文将调用另一个模板,并假设 vector 至少有四个元素。将其替换为您认为合适的任何逻辑。
关于C++嵌套模板参数查找失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18125082/