Disallow a specific function template instantiation

后端 未结 4 464
醉梦人生
醉梦人生 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条回答
  •  面向向阳花
    2021-02-06 00:22

    You could use a functor instead of a function:

    template
    struct convert { 
        T operator()(char const * in) const { return T(); } 
    };
    template<> struct convert;
    
    int main()
    {
        char const * str = "1234";
    
        int a = convert()( str );
        double b = convert()( str ); // error in this line
    
        return 0;
    }
    

    This will give you an error at the point of instantiation.

    By adding helper function you will get the wanted behaviour:

    template
    struct convert_helper { 
        T operator()(char const * in) const { return T(); } 
    };
    template<> struct convert_helper;
    
    template
    T convert( char const * in ) { return convert_helper()( in ); }
    
    int main()
    {
        char const * str = "1234";
    
        int a = convert( str );
        double b = convert( str );
    
        return 0;
    }
    

提交回复
热议问题