Using decltype for lambda comparators

I’m trying to understand the difference in the following two cases. In both, I introduce a comparator as a lambda function: auto comp = [](int x, int y) { return x%2 < y%2; }; But then, if I want to use it with a sort, I can simply write sort(vec.begin(), vec.end(), comp); while for a… Read More Using decltype for lambda comparators

Getting type of Class inside a Class Method

I want to determine the type of this variable inside a class method. For example, take the following example – #include <iostream> #include <cstdlib> #include <map> class Base{ }; using getPrintString = std::map<Base, std::string>; class A : public Base{ public: void print(getPrintString& stringMap){ std::string toPrint = stringMap[std::remove_reference<decltype(*this)>::type]; std::cout<<toPrint<<std::endl; } }; class B: public Base{ public:… Read More Getting type of Class inside a Class Method

Accessing variable template using decltype

A minimized example of my code showing the problem: #include <cassert> #include <iostream> #include <map> #include <string> template <typename T> const std::map<std::string, T> smap; template <> const std::map<std::string, bool> smap<bool>{{"a", false}}; int main() { std::map<bool, std::string> rmap{{false, "x"}}; for (const auto& [key, val] : rmap) { std::cerr << typeid(bool).hash_code() << "\n"; std::cerr << typeid(decltype(key)).hash_code() <<… Read More Accessing variable template using decltype

Why does a non-constexpr std::integral_constant work as a template argument?

My question is why the following code is valid C++: #include <iostream> #include <tuple> #include <type_traits> std::tuple<const char *, const char *> tuple("Hello", "world"); std::integral_constant<std::size_t, 0> zero; std::integral_constant<std::size_t, 1> one; template<typename T> const char * lookup(T n) { // I would expect to have to write this: // return std::get<decltype(n)::value>(tuple); // But actually this works:… Read More Why does a non-constexpr std::integral_constant work as a template argument?

How to initialise and return an std::array within a template function?

I’d like a template function that returns some initialisation. I did the following: #include<iostream> #include<array> template <typename T> inline static constexpr T SetValues() { if(std::is_integral<T>::value) { std::cout<<"int\n"; return T{1}; } else { std::cout<<"array\n"; T arr = {1,2,3,4}; return arr; } } int main() { int a = 6; std::array<int, 4> arr = {2,2,2,2}; a =… Read More How to initialise and return an std::array within a template function?