无法推导模板类型 [英] Can't deduce template type

查看:164
本文介绍了无法推导模板类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图传递一个迭代器作为模板参数到模板方法,但编译器抱怨:

I'm trying to pass an iterator as a template parameter to a template method, but the compiler complains that:

error C2783: 'void Test::Assert(std::vector<T>::const_iterator)':
could not deduce template argument for 'T'

产生错误的代码是:

#include "stdafx.h"
#include <iostream>
#include <vector>

class Test
{
    public:
        template <typename T>
        void Assert(typename std::vector<T>::const_iterator it)
        {
            std::cout << *it << std::endl;
        }
};

int _tmain(int argc, _TCHAR* argv[])
{
    Test test;

    std::vector<double> myVec;

    test.Assert(myVec.cbegin());

    return 0;
}



我猜想有一个简单的方法使这项工作,因为大多数的std算法可以从迭代器中推导出类型。

I'm guessing there is a simple way to make this work, since most of the std algorithms can deduce type from iterator.

推荐答案

原因是你有 T in是未推导的上下文

template <typename T>
void Assert(typename std::vector<T>::const_iterator it)

一个更简单的例子来理解为什么:

Consider a simpler case to understand why:

struct A { using type = int; };
struct B { using type = int; };
struct C { using type = int; };

template <typename T>
void Assert(typename T::type it) { ... }

Assert(5);

T 这是不可能确定。您必须显式提供类型为 Assert< A>(5)

What should T deduce as? It's impossible to determine. You'd have to explicitly provide the type... as something like Assert<A>(5).

另请参见什么是不受限制的上下文?


因为大多数std算法可以从迭代器中推导出类型。

since most of the std algorithms can deduce type from iterator.


$ b b

这是因为标准算法只是推导出迭代器类型,而不是容器类型。例如 std :: find is just:

That's because the standard algorithms just deduce the iterator type, not the container type. For instance std::find is just:

template <class InputIt, class T>
InputIt find( InputIt first, InputIt last, const T& value );

这里没有container的概念 - 它只是迭代器类型,需要推断。这是算法库的美的一部分。

There is no concept of "container" here at all - it's just the iterator type that needs to be deduced. That's part of the beauty of the algorithms library.

所以如果你想做的只是输出迭代器的内容,正确的函数只是:

So if what you want to do is just output the contents of the iterator, the correct function would just be:

template <typename Iterator>
void Assert(Iterator it)
{
    std::cout << *it << std::endl;
}



当调用 Assert(myVec.cbegin ) Iterator 将会被推导为 std :: vector< double> :: const_iterator ,这正是你想要的。

When you call Assert(myVec.cbegin()), Iterator will get deduced as std::vector<double>::const_iterator, which is exactly what you want.

这篇关于无法推导模板类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆