I would like to determine if a type is const or not using a template function, e.g.:
template <typename TTYPE> bool IsConst(TTYPE) {return false;}
template <typename TTYPE> bool IsConst(const TTYPE) {return true;}
But this does not work, any alternative suggestions?
What you're looking for is std::is_const
. If the type you give it is const, value
will be true
. If not, value
will be false
.
Here's the example you can find on that page:
#include <iostream>
#include <type_traits> //needed for is_const
int main()
{
std::cout << boolalpha; //display true/false, not 1/0
std::cout << std::is_const<int>::value << '\n'; //int isn't const
std::cout << std::is_const<const int>::value << '\n'; //const int is const
}
Output:
false
true
Since you tried making your own, I would recommend you look through the possible implementation that is provided to get a feel of how these things work, in case you do need to make one in the future. It is a good learning experience.
Consider the following code:
#include <iostream>
template<typename T>
struct isConst
{
static bool result;
};
template<typename T>
struct isConst<const T>
{
static bool result;
};
template<typename T>
bool isConst<T>::result = false;
template<typename T>
bool isConst<const T>::result = true;
int main()
{
std::cout << std::boolalpha;
std::cout << isConst<int>::result << "\n";
std::cout << isConst<const int>::result << "\n";
std::cout << isConst<const char>::result << "\n";
std::cout << isConst<char*>::result << "\n";
std::cout << isConst<const float>::result << "\n";
return 0;
}
I solve your problem with template specializations. When T
is const
the specialized (second) version is called automatically. If you compile and run this code you will get:
false
true
true
false
true
Your version doesn't work, because you redefine the IsConst
function (it is forbidden and causes compiler error)
Note: I changed the result()
function with a static variable. It also works and it's faster.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With