Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine constness using template functions in C++

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?

like image 522
user1432452 Avatar asked Jun 02 '12 13:06

user1432452


2 Answers

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.

like image 191
chris Avatar answered Nov 15 '22 12:11

chris


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.

like image 32
Rontogiannis Aristofanis Avatar answered Nov 15 '22 10:11

Rontogiannis Aristofanis