c++ - 如何在模板函数或类中实例化包含类型的容器变量?

标签 c++ c++11 templates c++14 decltype

如何在模板函数或类中实例化包含类型的容器变量?

我根据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;
}

最佳答案

您必须删除引用(使用 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;
}

关于c++ - 如何在模板函数或类中实例化包含类型的容器变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44218308/

相关文章:

c++ - 在 C++ 中不在整个 std::string 中打印引号给出负 ASCII 值?

c++ - __FILE__ 编译时的宏操作处理

c++ - C++ 标准库是否提供更紧凑和更通用的删除删除习惯用法?

c++ - 来自 C++ 中不同基类的模糊函数

c++ - 基于 OpenGL 的 UI 的几何表示

c++11: 委托(delegate)构造函数 - 无法选择构造函数模板?

c++ - std::unique_ptr 如何没有大小开销?

c++ - 未指定的模板参数

c++ - 如何在C++中创建使用给定伪代码递归的可变参数函数?

c++ - 排列网格大小和 block 大小