代码之家  ›  专栏  ›  技术社区  ›  Albert

C++:“非命名空间范围中的显式专用化”错误

  •  9
  • Albert  · 技术社区  · 15 年前
    template<typename T1, typename T2>
    class Bimap {
    public:
        class Data {
        private:
            template<typename T> Data& set(T);
            template<> Data& set<T1>(typename T1 v) { /*...*/ }
        };
    };
    

    这给了我一个错误:

    error: explicit specialization in non-namespace scope 'class Bimap<T1, T2>::Data'

    2 回复  |  直到 15 年前
        1
  •  16
  •   Anycorn    15 年前

    单向忘记模板,重载:

    Data& set(T1 v) { /*...*/ }
    

    但这里有一个技巧,我有时会用到

    您可以在类中专门化类模板:

    class {
        template<typename T>
        struct function_ {
            static void apply(T);
        };
    
        template<>
        struct function_<int> {
            ...
        };
    
        template<typename T>
        void function(T t) { return function_<T>::apply(t); }
    
        2
  •  0
  •   kenny mccormick    13 年前

    我有一个类似的问题,当我想添加一个“修剪过剩的能力”的定制容器。std::vector swap技巧和更改现有容器的声明都是无效的选项。所以我想到了这个:

    template <class T, bool isPtr> struct DeleteImp
    {
        static void Trim(T* to, unsigned int count);
    };
    
    template <class T> struct DeleteImp<T, false>       
    {
        static void Trim(T* to, unsigned int count) {}
    };
    
    template <class T> struct DeleteImp<T, true>        
    {
        static void Trim(T* to, unsigned int count)
        {
            for(unsigned int i=0; i<count; i++)
                delete to[i];
        }
    };
    

    由我的容器使用,如下所示:

    DeleteImp<T, TypeTraits<T>::isPointer>::Trim(buf + length, truelength-length);
    

    你也可以看看这个 resource .