C++ templates that accept only certain types

前端 未结 14 2411
一整个雨季
一整个雨季 2020-11-22 11:37

In Java you can define generic class that accept only types that extends class of your choice, eg:

public class ObservableList {
  ...
         


        
14条回答
  •  太阳男子
    2020-11-22 11:45

    I suggest using Boost's static assert feature in concert with is_base_of from the Boost Type Traits library:

    template
    class ObservableList {
        BOOST_STATIC_ASSERT((is_base_of::value)); //Yes, the double parentheses are needed, otherwise the comma will be seen as macro argument separator
        ...
    };
    

    In some other, simpler cases, you can simply forward-declare a global template, but only define (explicitly or partially specialise) it for the valid types:

    template class my_template;     // Declare, but don't define
    
    // int is a valid type
    template<> class my_template {
        ...
    };
    
    // All pointer types are valid
    template class my_template {
        ...
    };
    
    // All other types are invalid, and will cause linker error messages.
    

    [Minor EDIT 6/12/2013: Using a declared-but-not-defined template will result in linker, not compiler, error messages.]

提交回复
热议问题