add_const_ref

Tags:

/* From C++ Template Metaprogramming Exercise 2.0:

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

#include
#include
#include
#include
#include

using namespace std;
using namespace boost;

template
struct add_const_ref_helper;

template
struct add_const_ref
{
typedef typename
add_const_ref_helper::value>::type type;
};

template
struct add_const_ref_helper
{
typedef T type;
};

template
struct add_const_ref_helper
{
typedef T const& type;
};

int main()
{
cout << "Reference: " << is_same::type, int&>::value
<< endl; cout << "Non-Reference: " << is_same::type, const int&>::value
<< endl; return EXIT_SUCCESS; } [/code]

Comments

4 responses to “add_const_ref”

  1. Tony Avatar
    Tony

    Good codes to study!!!
    But where can I find the answers to other exercises? Or download them directly?

    Can anybody explain the implemention of is_reference in boost library?

  2. MKSeo Avatar
    MKSeo

    Thanks Tony.

    This code is written by me, and I did not try to solve all problems in the book. I don’t know where to find answers to the questions, and I guess only a few people are interested in solving all the problems, cuz they are too hard. You can post questions at boost mailing list although few will respond.

  3. HU Jiayi Avatar
    HU Jiayi

    hi, try this
    assert((boost::is_same<add_const_ref::type, const char ** & >::value)==true);

    I don’t understand what is the problem if I just specialize the add_const_ref as below (instead of using a helper metafunction)?

    template
    struct add_const_ref
    {
    typedef const T & type;
    };

    template
    struct add_const_ref
    {
    typedef T type;
    };

  4. Minkoo Seo Avatar
    Minkoo Seo

    HU Jiayi,

    Sorry that your template parameters are deleted. You could escape them before post or use

    [ code ]

    [ /code ]
    (surely without space)

    block.

    That’ll give you UI like this:

    template<foo bar>
    

    Sorry for inconvenience.

Leave a Reply

Your email address will not be published. Required fields are marked *