1

Let's say I have a class similar to:

template <typename T>
class MyClass
{
public:
    template <typename U>
    MyClass(const MyClass<U>&); // Not a copy constructor, as template.

    // How to delegate to above constructor?
    MyClass(const MyClass& a) : MyClass<T>(a) {}

    // ...
};

How to delegate the copy constructors to a (conversion) template constructor?

The code above results in a delegation cycle.

5
  • 1
    Normally, template argument deduction should be sufficient. The example is unclear because MyClass appears to inconsistently be a class or a class template. Commented Sep 27, 2022 at 22:20
  • Seems pretty clear to me. MyClass is a template and has a template argument T. It has a converting constructor template <typename U> MyClass(const MyClass<U>&); and OP wants to delegate to that from copy constructor. No idea if this is possible tho. Commented Sep 27, 2022 at 22:24
  • @FrançoisAndrieux MyClass is a class template with T being a template argument. Commented Sep 27, 2022 at 22:34
  • @BlueCannonBall Then update your question to make it clear. Provide a minimal example that compile except for the problematic constructor. I think that the easier workaround would be to have a "kind" of copy constructor with an extra argument. Commented Sep 28, 2022 at 0:08
  • Try : MyClass::MyClass<T>(a) {} Commented Sep 28, 2022 at 22:52

1 Answer 1

1

If the guess from @Yksisarvinen is correct then something like that should do:

template <class T> class MyClass
{
public:
    MyClass(const MyClass& a) : MyClass(a, true) {}

    template <class U>
    MyClass(const MyClass<U>& a) : MyClass(a, false) {}

private:
    template <class U>
    MyClass(const MyClass<U>& a, bool sameClass) 
    { 
        /* real code here */ 
    }
};

Alternatively, you can remove second copy constructor and put a default value for sameClass if you prefer (and make that constructor public).

Sign up to request clarification or add additional context in comments.

4 Comments

I would use a dummy tag instead of bool. std::is_same_v<T, U> has the information anyway, if required.
@Jarod42 What do you mean by dummy tag?
@Jarod42 Not a bad idea to use a dummy tag... I just made as simple as possible.
@BlueCannonBall: I mean using some struct dummy_tag{}; and then Demo. bool sameClass has a meaning (which might be used wrongly).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.