can I use SFINAE to selectively define a member variable in a template class?

后端 未结 4 1692
不知归路
不知归路 2020-12-28 18:43

So what I want to do is to create a template class which may or may not contain a member variable based on the template argument passed in. like following:

t         


        
4条回答
  •  轮回少年
    2020-12-28 19:06

    I have a workaround for this. Probably looks ugly but does resolve some of my issues

    First I define a type with zero size:

    typedef int zero[0];
    

    Next I create a macro:

    #ifndef VAR
    
    #define VAR(Enable,YourType,VarName) \    
    
    std::conditional< Enable,YourType,zero >::type VarName
    
    #endif
    

    Then a class like this:

    template < int Cond >
    class Foo
    {
        VAR(Cond == 0,int,var);
    
        void print()
        {
            if (!sizeof(var)) return;
            //...
        }
    };
    

    When you are using a result like var, check the size of it before using it. If the size is zero, it is invalid.

提交回复
热议问题