如何使用类型特征使数组到指针的转换明确?

2024-03-04

我想区分静态数组和指针。

以下示例由于以下原因无法编译具有精确匹配的数组到指针转换,使两者foo的可能候选人。

我能获得第二次超载吗foo使用类型特征明确选择?

#include <iostream>

template<typename T>
void foo(const T* str)
{
    std::cout << "ptr: " << str << std::endl;
}

template<typename T, size_t N>
void foo(const T (&str)[N])
{
    std::cout << "arr: " << str << std::endl;
}

int main()
{
    foo("hello world"); // I would like the array version to be selected
    return 0;
}

您可以使用以下内容:

namespace detail
{
    template <typename T> struct foo;

    template <typename T>
    struct foo<T*>
    {
        void operator()(const T* str) {std::cout << "ptr: " << str << std::endl;}
    };

    template <typename T, std::size_t N>
    struct foo<T [N]>
    {
        void operator()(const T (&str)[N]) {std::cout << "arr: " << str << std::endl;}
    };
}

template<typename T>
void foo(const T& t)
{
    detail::template foo<T>()(t);
}

实例 https://ideone.com/Wn5Yjb

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用类型特征使数组到指针的转换明确? 的相关文章

随机推荐