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?
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;