C++ Template Metaprogramming exercise 2-0

2-0.

Write a unary metafunction add_const_ref<T> that returns T if it is a reference type, and otherwise returns T const&. Write a program to test your metafunction. Hint: you can useboost::is_same to test the results.

Ans:

#include <boost/type_traits.hpp>
template < bool, typename T>
struct type_traits
{
typedef T type;
};
template < typename T >
struct type_traits<false, T>
{
typedef const T& type;
};
template <typename T>
struct add_const_ref
{
typedef typename type_traits<boost::is_reference<T>::value, T>::type type;
};
class A
{
};
typedef int (*funcPointer)(A) ;
int main()
{
bool l_bRes = boost::is_same< const int&, add_const_ref<int>::type >::value;
std::cout << “1. add_const_ref<int>::type is const int& ? ” << l_bRes << std::endl;

        l_bRes = boost::is_same< const int&, add_const_ref<int&>::type >::value;
std::cout << “2. add_const_ref<int&>::type is const int& ? ” << l_bRes << std::endl;

        l_bRes = boost::is_same< int&, add_const_ref<int&>::type >::value;
std::cout << “3. add_const_ref<int&>::type is int& ? ” << l_bRes << std::endl;

        l_bRes = boost::is_same< const A&, add_const_ref<A>::type >::value;
std::cout << “4. add_const_ref<A>::type is const A& ? ” << l_bRes << std::endl;

        l_bRes = boost::is_same< const funcPointer&, add_const_ref< funcPointer >::type >::value;
std::cout << “5. add_const_ref<funcPointer>::type is const funcPointer& ? ” << l_bRes << std::endl;
}

Result:

1. add_const_ref<int>::type is const int& ? 1

2. add_const_ref<int&>::type is const int& ? 0

3. add_const_ref<int&>::type is int& ? 1

4. add_const_ref<A>::type is const A& ? 1

5. add_const_ref<funcPointer>::type is const funcPointer& ? 1

Note the way we define a function pointer type in above sample code;

About xiongzou
a passionate C/C++ programmer

Leave a comment