How to avoid decay with template parameter deduction

前端 未结 2 2040
萌比男神i
萌比男神i 2021-01-04 05:28

Simplified:

// CHAR_TYPE == char, wchar_t, ...
template 
void Foo(CHAR_TYPE const (&value)[CHAR_COUNT]) no         


        
相关标签:
2条回答
  • 2021-01-04 06:19

    One idea that works is to remove the pointer and simply have T instead, with a std::enable_if_t<std::is_pointer<T>::value> guard. Simplified example below:

    #include <iostream>
    #include <type_traits>
    
    template<class T, size_t N>
    void f(T const (&) [N])
    {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
    }
    
    template<class T, std::enable_if_t<std::is_pointer<T>::value>* = nullptr >
    void f(T)
    {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
    }
    
    int main()
    {
        const char* str = "test";
        char str2[]{"test2"};
    
        f(str);
        f(str2);
    }
    

    Live on Coliru

    0 讨论(0)
  • 2021-01-04 06:25

    Taking the argument by (const) reference blocks array-to-pointer decay during template argument deduction. See [temp.deduct.call]/2. So:

    template <typename CHAR_TYPE>
    void Foo(CHAR_TYPE const* const & value) noexcept
    {
        TRACE("const ptr");
        // perform a bit of logic and forward...
    }
    
    0 讨论(0)
提交回复
热议问题