C++ template specialization for pointer?

前端 未结 3 1857
青春惊慌失措
青春惊慌失措 2020-12-19 04:43

I read book < C++ Templates - the Complete Guide > and learned template specialization for pointer. (maybe I misunderstand this part of the book)

(1) Here\'s my s

相关标签:
3条回答
  • 2020-12-19 05:20

    Two problems:

    1. You are not allowed to partially specialise a function.

    2. The behaviour of (void*)0x25 is undefined. With the exception of nullptr, you are not allowed to set a pointer to memory you don't own, with the exception of one past the final element of an array and one past the address of a scalar.

    0 讨论(0)
  • 2020-12-19 05:25

    The error message told you what is wrong:

    non-type partial specialization ‘Function<T*>’ is not allowed
    

    You can only partially specialize types (classes). You've tried to partially specialize a function. Functions are not types; you can only fully specialize them.

    0 讨论(0)
  • 2020-12-19 05:30

    as you've been already told, partial specialization of function templates are not allowed. You can use std::enable_if for this:

    template <typename T, typename std::enable_if_t<!std::is_pointer<T>::value>* = 0>
    void func(T val) { std::cout << val << std::endl; }
    
    template <typename T, typename std::enable_if_t<std::is_pointer<T>::value>* = 0>
    void func(T val) { func(*val); }
    

    If you are looking for simpler syntax, wait for concepts

    0 讨论(0)
提交回复
热议问题