Mukul M.
Mukul M.

Reputation: 541

C++ Compile-Time Conditional Run-Time Statements

Is there a way to, at compile-time, decide on one of two run-time code paths? I am aware that function overloading can be used to accomplish this feat, but then the code size increases because both of my functions are compiled and linked into the program. Is there a way to avoid this size overhead?

Essentially, what I want to do is:

#include <boost/mpl/if.hpp>
#include <boost/type_traits/is_abstract.hpp>

template <class T>
    class X
{
    public:
        void copy_t(T &old_t)
        {
            //
            // if T is abstract, (meaning that t is a pointer)
            //
            t = old_t.clone();

            //
            // else
            //
            t = old_t;
        }   

    private: 
        typename boost::mpl::if_<boost::is_abstract<T>, T *, T>::type t;
};

The only way I know involves overloaded member functions:

template <class T>
    class X
{   
    public:
        void copy_t(T &old_t)
        {   
            t = make_copy(old_t, t); 
        }   

    private:
        T *make_copy(T &old_t, T *t) 
        {   
            return old_t.clone();
        }   

        T &make_copy(T &old_t, T &t) 
        {   
            return old_t;
        }   

        typename boost::mpl::if_<boost::is_abstract<T>, T *, T>::type t;
};

But now, two make_copy member functions are compiled and linked into the program, even though X may only ever be instantiated with an abstract class template parameter, in which case, only one of them is needed.

Upvotes: 1

Views: 904

Answers (1)

James Kanze
James Kanze

Reputation: 153977

From your examples, it looks like the functions are members of a class template. If so, they will only be instantiated if they are actually used; if overload resolution always chooses one of them, the other will never be instantiated.

This is a critical rule for a lot of meta-programming techniques. It's not rare in such cases that the function which isn't instantiated would cause compile time errors if it was instantiated.

Upvotes: 3

Related Questions