Search code examples
c++boostc++03boost-mplboost-preprocessor

Using boost::mpl, how can I get how many template classes are not "Empty", and call some macro with this number?


I want to call a macro with some arguments depending on the result of boost::mpl::eval_if (or a similar function) that could give how many template arguments are not empty. Say we have some pseudocode like the following:

struct EmptyType {  };
template<class arg1=EmptyType, class arg2=EmptyType, class arg3=EmptyType>
class my_class
{
     eval_if<is_not_same<arg1, EmptyType>, FILL_MY_CLASS_DEFINE(1)> else      
     eval_if<is_not_same<arg2, EmptyType>, FILL_MY_CLASS_DEFINE(2)> else
     eval_if<is_not_same<arg3, EmptyType>, FILL_MY_CLASS_DEFINE(3)>;
};

I am trying to fill my class with some content depending on how many arguments are EmptyType. I wonder how such thing can be done in C++03 via Boost.MPL/Preprocessor or some other Boost library?


Solution

  • You don't need preprocessor or mpl. Partial specialization is you need:

    Edit This works in C++03, see it live: https://ideone.com/6MaHJ

    #include <iostream>
    #include <string>
    
    struct EmptyType {  };
    
    template<class  arg1=EmptyType, class arg2=EmptyType, class arg3=EmptyType>
    class my_class
    {
        // FILL_MY_CLASS_DEFINE(3)
    };
    template<class  arg1, class arg2>
    class my_class<arg1,arg2,EmptyType>
    {
        // FILL_MY_CLASS_DEFINE(2)
    };
    template<class  arg1>
    class my_class<arg1,EmptyType,EmptyType>
    {
        // FILL_MY_CLASS_DEFINE(1)
    };
    template<>
    class my_class<EmptyType,EmptyType,EmptyType>
    {
        // FILL_MY_CLASS_DEFINE(0)
    };
    
    int main(int argc, const char *argv[])
    {
        my_class<std::string, double, int> a;
        my_class<std::string, int> b;
        my_class<void> c;
    
        return 0;
    }