3

I have a function template in namespace

namespace sft
{
template <typename To, typename From>
auto safe_cast(From from) -> To
{
    // assert cast
    return static_cast<To>(from);
}
} // namespace sft

Now I want to bring this template function to local namespace (in this example to global namespace). I try to do it through templated function pointer.

template <typename To, typename From>
constexpr To (*safe_cast)(From) = &sft::safe_cast<To, From>;

However when I tried to call safe_cast without namespace prefix:

auto main() -> int
{
    return safe_cast<char>(-300);
}
I have a problem with template deduction using GCC 14.2
<source>: In function 'int main()':
<source>:16:26: error: wrong number of template arguments (1, should be 2)
   16 |     return safe_cast<char>(-300);
      |                          ^
<source>:12:16: note: provided for 'template<class To, class From> constexpr To (* const safe_cast)(From)<To, From>'
   12 | constexpr To (*safe_cast)(From) = &sft::safe_cast<To, From>;

How can it be done or is there any other way how to bring function template to local namespace without using namespace prefix?

see Godbolt

EDIT: I know that it is possible to use 'safe_cast<char,int>(-300)' but it means that the second type need to provided, which is error prone. The 'sft::safe_cast(-300)' is possible without using the second template parameter. How to do the same without using prefix?

0

1 Answer 1

4

You can't create a variable template and leave any template parameters to be deduced when used.

Fortunately, you don't have to. Just replace your variable template with a using-declaration:

using sft::safe_cast;

Demo

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

2 Comments

I updated the Godbolt link because the OP wanted to pass only the char (To) type and your solution works with it as well.
@wohlstad Ah, thanks! I missed removing that when tinkering :-)

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.