0

How do I instantiate a variable of a container containing type inside a template function or class ?

I added typename on the recommendation of dependent scope; need typename in front;

But still could not make it work.

#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;
}
Manish
  • 668
  • 1
  • 6
  • 13

1 Answers1

1

You have to remove the reference (with 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;
}
max66
  • 65,235
  • 10
  • 71
  • 111
  • Thank you. It worked, i was trying to do the same, but was not able to figure out the exact way to do it. – Manish May 27 '17 at 15:16
  • @KinanAlSarmini - Obvious; but the OP show us two different functions where uses `decltype()`; the first one works, the second one doesn't. He can use `T::value_type` in both but is important (IMHO) to show how to use `decltype` with reference variables. – max66 May 27 '17 at 15:21