如何在模板函数或类中实例化包含类型的容器的变量?
我在dependent scope; need typename in front;
的推荐下添加了typename但仍然无法使其发挥作用。
#include <iostream>
#include <array>
#include <type_traits>
#include <typeinfo>
#include <vector>
using namespace std;
template<class T>
void crazy_func_byvalue(T data){
typename decltype(data)::value_type var; //typename added here
cout<< typeid(var).name();
cout<<endl;
return;
}
template<class T>
void crazy_func_byaddress(T& data){
typename decltype(data)::value_type var;
cout<< typeid(var).name();
cout<<endl;
return;
}
class test{
};
int main(){
std::array<double,12> var1={1593,-88517,14301,3200,6,-15099,3200,5881,-2593,11,57361,-92990};
decltype(var1)::value_type x;
std::vector<test> var2;
crazy_func_byvalue(var1);
crazy_func_byvalue(var2);
crazy_func_byaddress(var1); //error: 'std::array<double, 12ul>&' is not a class, struct, or union type
crazy_func_byaddress(var2); //error: 'std::vector<test>&' is not a class, struct, or union type
//cout<<"It is working here";
return 0;
}
答案 0 :(得分:1)
您必须删除引用(使用std::remove_reference
)
template<class T>
void crazy_func_byaddress(T& data){
typename std::remove_reference<decltype(data)>::type::value_type var;
cout<< typeid(var).name();
cout<<endl;
return;
}