astrophobia
astrophobia

Reputation: 889

conditional member function declaration based on variadic template length

I want to define a different set of member functions in my class based on the length of the class's variadic template. Is this possible? For example is something like this possible?

template<class T, std::size_t... T2>
class S {
   public:
      #ifdef SIZE_OF_T2_GREATER_THAN_ZERO
         void f1(params1);
      #else
         void f2(params2);
      #endif
};

So if the length of T2... is greater than zero I want function f1 defined while if there are no parameters in T2... I want some function f2 defined. Is this possible?

Upvotes: 2

Views: 170

Answers (2)

Kahler
Kahler

Reputation: 1140

If you make the member function templated based on sizeof...() applied to T2...

template<std::size_t L = sizeof...(T2)>

You can conditionally compile the functions using std::enable_if, as in:

template<class T, std::size_t... T2>
struct my_struct{
    template<std::size_t L = sizeof...(T2)>
    typename std::enable_if<L!=0, void>::type f1()
    {
        std::cout<< "this class has T2...\n";
    }

    template<std::size_t L = sizeof...(T2)>
    typename std::enable_if<L==0, void>::type f2()
    {
        std::cout<< "this class has nooooo T2\n";
    }
};

I`ve made a working example at http://cpp.sh/6jskq

Upvotes: 2

Evg
Evg

Reputation: 26302

Basic idea:

template<std::size_t size_of_t2, class T>
struct Base
{ 
    void f1(params1);
};

template<class T>
struct Base<0, T>
{
    void f2(params2);
};

template<class T, std::size_t... T2>
struct S : Base<sizeof...(T2), T>
{ };

Alternatively, you could have both f1 and f2 present in S and then guard their usage by static_assert (note that member functions of a class template are not instantiated unless they are used):

template<class T, std::size_t... T2>
struct S
{
    void f1(params1)
    { 
        static_assert(sizeof...(T2) > 0);
        ...
    }

    void f2(params2)
    { 
        static_assert(sizeof...(T2) == 0);
        ...
    }
};

Upvotes: 2

Related Questions