Default values in templates with template arguments ( C++ )

后端 未结 6 965
名媛妹妹
名媛妹妹 2020-12-05 05:03

Assume I have a template (called ExampleTemplate) that takes two arguments: a container type (e.g. list, vector) and a contained type (e.g. float, bool, etc). Since containe

6条回答
  •  猫巷女王i
    2020-12-05 05:12

    Perhaps you'd prefer this:

    #include 
    #include 
    
    using namespace std;
    
    template 
    class ForExamplePurposes {
        typedef typename Container::value_type T;
        Container items;
    public:
    };
    
    int main()
    {
        ForExamplePurposes< list > a;
        ForExamplePurposes< vector > b;
    }
    

    This uses "static duck typing". It is also a bit more flexible as it doesn't force the Container type to support STL's Allocator concept.


    Perhaps using the type traits idiom can give you a way out:

    #include 
    #include 
    
    using namespace std;
    
    struct MyFunkyContainer
    {
        typedef int funky_type;
        // ... rest of custom container declaration
    };
    
    // General case assumes STL-compatible container
    template 
    struct ValueTypeOf
    {
        typedef typename Container::value_type type;
    };
    
    // Specialization for MyFunkyContainer
    template <>
    struct ValueTypeOf
    {
        typedef MyFunkyContainer::funky_type type;
    };
    
    
    template 
    class ForExamplePurposes {
        typedef typename ValueTypeOf::type T;
        Container items;
    public:
    };
    
    int main()
    {
        ForExamplePurposes< list > a;
        ForExamplePurposes< vector > b;
        ForExamplePurposes< MyFunkyContainer > c;
    }
    

    Someone who wants to use ForExamplePurposes with a non-STL-compliant container would need to specialize the ValueTypeOf traits class.

提交回复
热议问题