【问题标题】:How do I instantiate a variable of a container containing type inside a template function or class?如何实例化包含模板函数或类内的包含类型的容器的变量?
【发布时间】:2017-05-27 14:56:36
【问题描述】:

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

我在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;
}

【问题讨论】:

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


    【解决方案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;
    }
    

    【讨论】:

    • 谢谢。它有效,我试图做同样的事情,但无法找出确切的方法。
    • @KinanAlSarmini - 很明显;但是 OP 向我们展示了两个使用 decltype() 的不同功能;第一个有效,第二个无效。他可以在两者中使用T::value_type,但重要的是(恕我直言)展示如何将decltype 与引用变量一起使用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多