Implicit conversion constructor with template classes

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • flopbucket

    Implicit conversion constructor with template classes

    Hi,

    If I have:

    template<class T>
    class X
    {
    .....
    };

    then:

    template<class U>
    class Y
    {
    public:
    typedef X<U> NormalType;
    typedef X<const U> ConstType;

    NormalType foo() { return NormalType(); }
    };

    How can I (or can I?) have conversion from NormalType to ConstType so
    the following would work:

    Y<int> bar;
    ConstType i = bar.foo();

    Can I have a constructor in Y like "Y(const Y<const T>&)" to provide
    implicit conversion? If I do something in Y like:

    template<class Z>
    Y(const Z&)

    That would apply to any type and try to convert, wouldnt it?

    Is there a way I can specify I can accept a type "const T" when the
    template is instantiated with just T?


    Thanks for any tips.

  • Tom Widmer

    #2
    Re: Implicit conversion constructor with template classes

    flopbucket wrote:[color=blue]
    > Hi,
    >
    > If I have:
    >
    > template<class T>
    > class X
    > {
    > ....
    > };
    >
    > then:
    >
    > template<class U>
    > class Y
    > {
    > public:
    > typedef X<U> NormalType;
    > typedef X<const U> ConstType;
    >
    > NormalType foo() { return NormalType(); }
    > };
    >
    > How can I (or can I?) have conversion from NormalType to ConstType so
    > the following would work:
    >
    > Y<int> bar;
    > ConstType i = bar.foo();[/color]

    Presumably you can modify Y's code. Can you modify X's too?
    [color=blue]
    > Can I have a constructor in Y like "Y(const Y<const T>&)" to provide
    > implicit conversion? If I do something in Y like:
    >
    > template<class Z>
    > Y(const Z&)
    >
    > That would apply to any type and try to convert, wouldnt it?[/color]

    Yes, but it would convert it to a Y, not an X.
    [color=blue]
    > Is there a way I can specify I can accept a type "const T" when the
    > template is instantiated with just T?[/color]

    You have to be careful, since the type obviously needs to work with
    const. In your case, something like this should work:

    template <class T>
    class X
    {
    public:
    X(X<const T> const&); //construct from const.
    };

    template <class T>
    class X<const T>
    {
    //no const T constructor
    };

    You could move common functionality into a base class to avoid excessive
    repetition.

    Tom

    Comment

    Working...