2013-03-09 91 views
1

你能帮我理解为什么这段代码不能编译?我想了解C++模板。功能模板

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

template <class myT> 
void myfunction (myT i) 
{ 
    std::cout << ' ' << i; 
} 

int main() 
{ 
    double array1[] = {1.0, 4.6, 3.5, 7.8}; 

    std::vector<double> haystack(array1, array1 + 4); 

    std::sort(haystack.begin(), haystack.end()); 

    std::cout << "myvector contains:"; 
    for_each (haystack.begin(), haystack.end(), myfunction); 
    std::cout << '\n'; 
    return 0; 
} 
+0

如果不能编译,至少出错。 – chris 2013-03-09 03:17:33

+0

另外,您可能只想包含“using namespace std;”所以你不必继续写“std ::” – jrubins 2013-03-09 03:19:09

+3

@jrubins,这通常被认为是[坏习惯](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-考虑 - 一个坏实践,在-C)。 – chris 2013-03-09 03:20:33

回答

1

模板就像一个蓝图。可能有很多myfunction,每个都采取不同的类型。你当你实例化它在这种情况下,告诉编译器使用哪一个给类型:

for_each (haystack.begin(), haystack.end(), myfunction<double>); 
                 ^^^^^^^^ 
+0

,但我认为for_each()函数将传递给myfunction()两倍,这种方式myfunction()将实例化,不是吗? – 2013-03-09 08:28:21

+0

@HovnatanKarapetyan,事情是,它需要一个特定的功能,而不是功能的蓝图。每种类型都有自己的功能,并且您知道您希望使用哪种类型。另外,您可能并不总是希望使用存储在容器中的类型。假设你必须输入双打,并打印出最大的整数。你可以使用'std :: istream_iterator '得到你的输入,然后复制到'std :: ostream_iterator '输出。 – chris 2013-03-09 14:02:09

2

因为你传递myfunction的功能,它不能工作了,自动使用哪个模板,所以你必须告诉它myfunction<double>

这不适用于直接调用它,如myfunction(2.0),因为作为一个方便,编译器会根据您给它的参数找出使用哪个模板。