tuket
tuket

Reputation: 3951

Alias for std::dynamic_pointer_cast

I'm trying to create an alias for std::dynamic_pointer_cast but can't write something that compiles.

This is the way I'm trying:

template <typename T1, typename T2>
using dcast = std::dynamic_pointer_cast<T1, T2>;

What is wrong with it?

Compiler errors:

gcc: dynamic_pointer_cast' in namespace 'std' does not name a type'

clang: no type named 'dynamic_pointer_cast' in namespace 'std'

VS: syntax error: identifier 'dynamic_pointer_cast'

Try it: https://godbolt.org/g/akbqiu

EDIT: As Brian pointed out, you can only alias types not functions.

I've tried with the following code:

template <typename T1, typename T2>
auto& dcast = std::dynamic_pointer_cast<T1, T2>;

Which seems to compile on itself, but once you try to call it it gives the following error:

error: wrong number of template arguments (1, should be 2)

You can call std::dynamic_pointer_cast with only one template argument though. Which could be the alternative?

Upvotes: 2

Views: 264

Answers (1)

HolyBlackCat
HolyBlackCat

Reputation: 96719

As said in comments, you have to make a new function:

template <class T, class U> 
std::shared_ptr<T> dcast(const std::shared_ptr<U> &r) noexcept
{
    return std::dynamic_pointer_cast<T>(r);
}

Upvotes: 3

Related Questions