Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to refer to a user-defined conversion template in a using declaration?

In a class B inheriting from class A, it's possible to use a using declaration to bring members of A into B, even templates, like this:

struct A {
    template <typename T>
    void foo();
};

struct B : private A {
    using A::foo;
};

But can it be done for conversion templates?

struct A {
    template <typename T>
    operator T();
};

struct B : private A {
    using A::operator /* ??? */;
};

There seems to be no way of referring to the template by name, but I would love to be proven wrong or get some clarification.

like image 503
Apples Avatar asked Oct 22 '19 04:10

Apples


People also ask

What is an user-defined type conversion?

Conversion functions define conversions from a user-defined type to other types. These functions are sometimes referred to as "cast operators" because they, along with conversion constructors, are called when a value is cast to a different type.

What is a conversion function in C++?

You can define a member function of a class, called a conversion function, that converts from the type of its class to another specified type.

Is user-defined conversion that forces an expression to be of specific type?

Answer. An implicit type conversion is automatically performed by the compiler when differing data types are intermixed in an expression. An explicit type conversion is user-defined conversion that forces an expression to be of specific type. An implicit type conversion is performed without programmer's intervention.


1 Answers

As a workaround, you can cast to the base class and convert it explicitly:

struct A {
    template <typename T>
    operator T() {
        return T{};
    }
};

struct B : private A {
    template <class T>
    operator T() {
        return static_cast<T>(static_cast<A&>(*this));
    }
};

int main() {
    A a;
    B b;
    int i_a = a;
    int i_b = b;
}
like image 58
Ayjay Avatar answered Sep 29 '22 05:09

Ayjay