首页 > C++模版函数的调用问题

C++模版函数的调用问题

假设有如下代码:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

template <typename T1>
void display(T1 x)
{
        cout << x << endl;
}

template <typename T2>
void fun1(const string msg, const vector<T2> vec)
{
        for_each(vec.begin(), vec.end(), display);
}

int main(int argc, char **argv)
{
        string msg("Hello world");
        vector<int> vec;

        vec.push_back(11);
        vec.push_back(12);
        vec.push_back(7);

        fun1(msg, vec);

        return 0;
}

为什么这段代码会出错?用的是C++98的标准,编译器是g++
display函数不用模版函数的时候就可以编译通过:

void display(int x)

display() 需要显示的类型就是T2,改成下面的用g++编译就可以了。

template<typename T2>
void fun1(const string msg, const vector<T2> vec)
{
        for_each(vec.begin(), vec.end(), display<T2>);
}

但是用clang 600.0.56 照样不能编译。定义fun1的时候直接报错:
candidate template ignored: couldn't infer template argument 'T'.
据说g++ 实现有错,我刚开始学,也不明白。


给display添加类型标记就可以了

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

template <typename T1>
void display(T1 x)
{
    cout << x << endl;
}

template <typename T2>
void fun1(const string msg, const vector<T2> vec)
{
    for_each(vec.begin(), vec.end(), display<T2>);
}

int main(int argc, char **argv)
{
    string msg("Hello world");
    vector<int> vec;

    vec.push_back(11);
    vec.push_back(12);
    vec.push_back(7);

    fun1<int>(msg, vec);

    return 0;
}

display是模板函数,在调用for_each的时候display还没有实例化,在for_each内部调用display的时候才会实例化display(这个时候会根据迭代器解引用返回的值来推导类型实例化),所以for_each这里是编译不过的

【热门文章】
【热门文章】