简体   繁体   English

基于可变模板长度的条件成员函数声明

[英]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. 因此,如果T2...的长度T2...大于零,我要定义函数f1而如果T2...中没有参数T2...我想定义一些函数f2 Is this possible? 这可能吗?

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): 或者,您可以在S同时包含f1f2 ,然后通过static_assert保护它们的使用(请注意,除非使用了它们,否则不会实例化类模板的成员函数):

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);
        ...
    }
};

If you make the member function templated based on sizeof...() applied to T2... 如果使成员函数基于应用于T2... sizeof...()模板化T2...

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

You can conditionally compile the functions using std::enable_if , as in: 您可以使用std::enable_if有条件地编译函数,如下所示:

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 我在http://cpp.sh/6jskq上做了一个工作示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM