Type traits with non-template variadic function

Discussion in 'C++' started by Qi, Oct 25, 2012.

  1. Qi

    Qi Guest

    I have some type traits to create different object based on
    different type. I would use non-template overload function
    to do it because it's easily to handle derived class.

    Sample code:

    SomeFoo * createFoo(...); // #1
    SomeFoo * createFoo(MyClass *); // #2

    #1 is a general trap-all function to catch all unhandled
    types. #2 is a traits for MyClass.

    The problem is, for a given type T, the function parameter
    should be always T * rather than T or T &, because the
    general "..." version can't handle non trivial T.

    That means, if I want to make traits for MyClass, I have to write,
    SomeFoo * createFoo(MyClass *);
    If I want to make traits for MyClass *, I have to write,
    SomeFoo * createFoo(MyClass **);

    There is always an extra pointer in the parameter, which is
    not good and quite confusing.

    So my question is, is there any way to eliminate the extra pointer
    if T is not always a pointer?

    There are two alternative solutions for it I can think of, neither
    is good enough:

    1, Use a trap all class.
    struct TrapAll { template<typename T> TrapAll(const T &) {} };
    Change the general function to
    SomeFoo * createFoo(TrapAll);
    It doesn't work if the class T has an implicit constructor,
    such as std::string, which will cause ambiguous.

    2, Change the general function to template.
    template <typename T>
    SomeFoo * createFoo(const T &);
    Then the derived class of MyClass will be handled by the template
    rather than #2 traits, which is wrong.

    Any suggestions?


    --
    WQ
     
    Qi, Oct 25, 2012
    #1
    1. Advertising

  2. Qi

    Qi Guest

    PS:
    For the alternative 2,
    > 2, Change the general function to template.

    It's possible to use some kind of enable_if and
    is_derived_from type traits to make it work for
    derived class.
    However, I would avoid it because I want the end
    user to create the traits, who may not know
    how to use those type traits.


    --
    WQ
     
    Qi, Oct 25, 2012
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Colin Walters
    Replies:
    2
    Views:
    540
    Ben Pfaff
    Feb 13, 2004
  2. Ross A. Finlayson
    Replies:
    19
    Views:
    636
    Keith Thompson
    Mar 10, 2005
  3. Replies:
    2
    Views:
    365
    Dave Thompson
    Feb 27, 2006
  4. Replies:
    5
    Views:
    382
  5. ray
    Replies:
    1
    Views:
    1,386
    Robert Kern
    Jun 4, 2010
Loading...

Share This Page