Omn*_*ous 7 c++ templates overloading c++14
我有以下代码:
template <typename T, ::std::size_t size>
using ary_t = T[size];
template <typename T, ::std::size_t size>
constexpr int call_me(ary_t<T const, size> &a)
{
int total = 10;
for (::std::size_t i = 0; i < size; ++i) {
total += a[i];
}
return total;
}
template <typename T>
constexpr int call_me(T const *a)
{
int total = 0;
for (int i = 0; a[i]; ++i) {
total += a[i];
}
return total;
}
#if 0
int t1()
{
return call_me("a test");
}
#endif
int t2()
{
char const * const s = "a test";
return call_me(s);
}
Run Code Online (Sandbox Code Playgroud)
并且可以正常工作,但是当删除#if 0周围的部分时t1,由于使用的模板不明确,因此无法编译。有什么方法可以强制call_me优先使用的数组版本?
我尝试了许多不同的技巧来完成这项工作。我尝试将, int...指针版本添加到模板参数列表中。我尝试删除const。我都尝试过。我什至尝试将指针版本制作为C样式的varargs函数(又名int call_me(T const *a, ...))。似乎没有任何作用。
我很高兴得到一个答案,该答案需要当前被认为可以成为C ++ 2a的东西。
有一个简单的解决方法:
template <typename T>
constexpr int call_me(T&& arg) {
if constexpr(std::is_pointer_v<std::remove_reference_t<T>>) {
return call_me_pointer(arg);
} else {
return call_me_array(arg);
}
}
Run Code Online (Sandbox Code Playgroud)
如果您接受添加间接级别,则可以添加未使用的参数来为数组版本提供优先级。
我是说
template <typename T, std::size_t size>
constexpr int call_me_helper (ary_t<T, size> &a, int)
{
int total = 10;
for (std::size_t i = 0; i < size; ++i) {
total += a[i];
}
return total;
}
template <typename T>
constexpr int call_me_helper (T const * a, long)
{
int total = 0;
for (int i = 0; a[i]; ++i) {
total += a[i];
}
return total;
}
template <typename T>
constexpr int call_me (T const & a)
{ return call_me_helper(a, 0); }
Run Code Online (Sandbox Code Playgroud)