2013-04-27 99 views
0

我正在尝试使用以下代码。非模板参数为什么不能通过std :: vector

#include <iostream> 
#include <vector> 

using namespace std; 

template <typename T, std::vector <T> myV> 
int fun() 
{ 
    cout <<" Inside fun() "<<endl; 
} 

int main(int argc, char ** argv) 
{ 
    std::vector<int> a; 
    fun<int,a>(); 
} 

我无法通过的std ::矢量MYV?但

代替的std ::向量,我可以能够使用类似模板 **,并乐趣()。

回答

0

你需要调用

fun<int, std::vector<int>>(); 

其传递std::vector<int>。如果你想传递的std::vector<int>一个实例(a),你将有你的函数定义修改为:

template<typename T> 
int fun(std::vector<T> v) 
{ 
    std::cout << "Inside fun()\n"; 
} 

int main() 
{ 
    std::vector<int> a; 
    fun(a); 
} 
+0

很好解释。 – Whoami 2013-04-27 10:59:51

1

什么三角支架推移必须是一个类型或一个编译时间常数;它不能是一个变量。虽然a的类型是vector<int>,a本身是vector<int>类型的对象;它不能作为模板参数之一进入三角括号。

另外,不能使用vector<T>作为模板函数的第二个参数:vector<T>是一种知道T后会变得完全知晓的类型。由于您已经有T作为模板参数,因此您可以在函数内部“免费”地声明vector<T>,而无需额外的模板参数。

最后,在C++ 11中,您可以使用decltype静态获取一个变量类型。例如,如果您修改代码以利用T单一类型的参数,你可以这样做:

#include <iostream> 
#include <vector> 

using namespace std; 

template <typename T> 
int fun() 
{ 
    cout <<" Inside fun() "<<endl; 
} 

int main(int argc, char ** argv) 
{ 
    std::vector<int> a; 
    // This is the same as calling fun<std::vector<int> >(); 
    fun<decltype(a)>(); 
    return 0; 
} 

Demo on ideone

+0

感谢您的回复。是否有可能使用std :: vector 作为模板参数?因为std :: vector 本身就是一个数据类型吧?纠正我,如果我错了。 – Whoami 2013-04-27 10:53:27

+0

@Whoami是的,可以使用'std :: vector '作为模板参数:任何类型,包括基于模板的类型。你不能使用的是'std :: vector'(没有''或其他类型的参数),因为它是一个模板名称,而不是一个类型。 – dasblinkenlight 2013-04-27 11:05:56

+0

所以,std :: vector是一个类模板,std :: vector 是它的专门化,它是一个有效的数据类型。如果我们仍然想提供std :: vector,那么我们需要使用template-template参数的概念。是这样吗 ? – Whoami 2013-04-27 11:10:31

相关问题