Getting type of Class inside a Class Method

Advertisements 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{… Read More Getting type of Class inside a Class Method

Accessing variable template using decltype

Advertisements 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?

Advertisements 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… 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?

Advertisements 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?