Disallow a specific function template instantiation

后端 未结 4 521
醉梦人生
醉梦人生 2021-02-05 23:59

I would like to define a template function but disallow instantiation with a particular type. Note that in general all types are allowed and the generic template works, I just w

4条回答
  •  闹比i
    闹比i (楼主)
    2021-02-06 00:27

    Consider Boost disable_if and Boost TypeTraits

    Take a look at How can I write a function template for all types with a particular type trait?

    This is an example:

    #include 
    #include 
    
    template
    T convert( char const * in, 
               typename boost::disable_if, T>::type* = 0 )
    { return T(); }
    
    
    int main()
    {
        char const * str = "1234";
    
        int a = convert( str );
        double b = convert( str );
        return 0;
    }
    


    This is the compilation error for the string

    double b = convert( str );
    

    1>.\simple_no_stlport.cpp(14) : error C2770: invalid explicit template argument(s) for 'T convert(const char *,boost::disable_if,T>::type *)' 1> .\simple_no_stlport.cpp(5) : see declaration of 'convert'

提交回复
热议问题