Defining a constant using template functions in C ++

I would like to determine if the type is const or not using a template function, for example:

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?

+5
source share
2 answers

What you are looking for std::is_const. If the type you specify is const, valuewill be true. If not, there valuewill be false.

Here is an example you can find on this 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
} 

Conclusion:

false
true

Since you were trying to make your own, I would recommend that you familiarize yourself with a possible implementation that is provided to understand how this works if you need to do this in the future. This is a good learning experience.

+11
source

:

#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;
}

. T const, () . , :

false
true
true
false
true

, IsConst ( )

: result() . .

+1

All Articles