2015-06-12 123 views
0

这是我的代码:模板专业化功能的C++

#include <iostream> 
using namespace std; 

template< typename T > 
T silnia(T w) { 
    cout << "not special" << endl; 
} 
template<> 
int silnia<int>(int x) { 
    cout << "special" << endl; 
} 

int main() { 

cout << silnia<double>(5) << endl; 
cout << silnia<int>(5) << endl; 

return 0; 
} 

这是输出:

not special 
nan 
special 
4712544 

有人可以帮助我了解那里有两个额外的线路是从哪里来的?

回答

5

你很可能得到一个编译器警告(至少)告诉你,你的模板Tint分别为返回,但你没有提供返回值,这是未定义的行为。你应该返回函数声明的类型。

template< typename T > 
T silnia(T w) { 
    cout << "not special" << endl; 
    return w; 
} 

template<> 
int silnia<int>(int x) { 
    cout << "special" << endl; 
    return x 
} 

为什么重要?因为您正在使用std::cout来尝试输出这些函数调用的返回值。

cout << silnia<double>(5) << endl; 
cout << silnia<int>(5) << endl; 
4

这两个函数模板都有返回类型,但实现不返回任何内容。您有未定义的行为,因为您正在尝试使用返回值。这与模板无关。

这是你的代码的固定版本:

#include <iostream> 
using std::cout; 
using std::endl; 

template< typename T > 
T silnia(T w) { 
    cout << "not special" << endl; 
    return w; 
} 
template<> 
int silnia<int>(int x) { 
    cout << "special" << endl; 
    return x; 
} 

int main() { 
    cout << silnia<double>(5) << endl; 
    cout << silnia<int>(5) << endl; 
} 

输出

not special 
5 
special 
5