Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deducing constness of type returned by function

Is there a way to tell whether a function returns a const or a non-const value? decltype works for references, but it won't work for non-reference types.

#include <type_traits>

template< typename >
struct print_type;      //undefined

int main(){
  auto lambda = []()->const int{ return 0; };
  print_type< decltype(lambda()) > dt;   //print_type< int >
  print_type< typename std::result_of<decltype(lambda)()>::type > ro;  
    //print_type< int >


  return 0;
}

I implemented a std::tuple transform function, that will call a function object on each tuple element and store the result in a new tuple composed of return types. This doesn't work for const return types, which is pretty surprising (but needed).

like image 571
tsuki Avatar asked Sep 17 '14 18:09

tsuki


1 Answers

For non built-in types, you can use std::is_const and decltype to get what you want.

Example:

#include <iostream>
#include <type_traits>

struct A {};

int main()
{
   std::cout << std::boolalpha;
   {
      auto lambda = []()->A{ return A(); };
      std::cout << std::is_const<decltype(lambda())>::value << std::endl;
   }

   {
      auto lambda = []()->const A{ return A(); };
      std::cout << std::is_const<decltype(lambda())>::value << std::endl;
   }

   return 0;
}

Output:

false
true
like image 84
R Sahu Avatar answered Sep 18 '22 10:09

R Sahu