C++ - What is the purpose of function template specialization? When to use it?

前端 未结 6 1940
北恋
北恋 2021-01-13 11:31

Learning C++, came upon function templates. The chapter mentioned template specialization.

  1. template <> void foo(int);

6条回答
  •  南笙
    南笙 (楼主)
    2021-01-13 11:57

    One case for template specialization which is not possible with overloading is for template meta-programming. The following is real code from a library that provides some of it services at compile time.

    namespace internal{namespace os{
        template  std::ostream& get();
    
        struct stdout{};
        struct stderr{};
    
        template <> inline std::ostream& get() { return std::cout; }
        template <> inline std::ostream& get() { return std::cerr; }
    }}
    
    // define a specialization for os::get()
    #define DEFINE_FILE(ofs_name,filename)\
        namespace internal{namespace os{                        \
            struct ofs_name{                                    \
                std::ofstream ofs;                              \
                ofs_name(){ ofs.open(filename);}                        \
                ~ofs_name(){ ofs.close(); delete this; }                    \
            };                                          \
            template <> inline std::ostream& get(){ return (new ofs_name())->ofs; }   \
        }}                                              \
        using internal::os::ofs_name;   
    

提交回复
热议问题