Force type of C++ template

前端 未结 6 1260
难免孤独
难免孤独 2020-12-28 21:34

I\'ve a basic template class, but I\'d like to restrain the type of the specialisation to a set of classes or types. e.g.:

template 
class          


        
6条回答
  •  萌比男神i
    2020-12-28 22:04

    Yust a quick idea, I'm sure there are better approaches:

    template  struct protector {
    static const int result = 1;
    };
    
    template <> struct protector {
    static const int result = -1;
    };
    
    template  
    class MyClass
    {
       private:
         char isfine[protector::result];
    };
    

    It might be better, however, to put a fat comment over your code to keep users from instantiating with the wrong types :-)

提交回复
热议问题