C++嵌套模板参数查找失败

标签 c++ templates c++11

考虑:

#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/

相关文章:

c++ - 大内存块的快速内存分配

c++ - 组合模板和对象类

c++ - 在 MFC 中创建标尺栏

c++ - 如何判断模板类型是基本类型还是类

c++ - '.size' 的左边必须有类/结构/union

c++ - 在运行时使用用户定义的文字

c++11 - 带有 boost::adaptor::indexed 的基于范围的 for 循环

c++ - 临时对象是 xvalues 吗?

c++ - 在 Mac OSX 上的 Sublime Text 3 中运行 C++

c++ 转换运算符没有候选更好