Search code examples
c++templatestemplate-specialization

C++ Function full specialization giving error


I have the below code to understand function full specialization concept:

//Function Full specialization is legal but not partial
class Wrapper
{
public:
    void setValue(int x) { }
};

template <typename R, typename T>
R* create(T t)
{
    return new R(t);
}
template <>
Wrapper* create<Wrapper, int>(int n) // fully specialized now -> legal...
{
    Wrapper* w = new Wrapper();
    w->setValue(n);
    return w;
}

//template <typename T>
//Wrapper* create<T, int>(T n) // partial specialized now -> illegal...
//{
//    Wrapper* w = new Wrapper();
//    w->setValue(n);
//    return w;
//}

//T
int main()
{
    create< Wrapper, int>(2);
    create< int, int>(2);
}

The above code compiles and execute fine as expected but when I change the full specialization function signature to something else:

template <>
const char* create<const char*, int>(int n) // fully specialized now -> legal...
{
    //Wrapper* w = new Wrapper();
    //w->setValue(n);
    //return w;
    return "Hi";
}

OR

template <>
char* create<char, char>(int n) // fully specialized now -> legal...
{
    return (char*)"HI";
}

Error:

explicit specialization 'const char *create<const char*,int>(int)' is not a specialization of a function template   Specialization and Overloading

explicit specialization 'char *create<char,char>(int)' is not a specialization of a function template   Specialization and Overloading

Why is the error being reported by code and how to fix the same?


Solution

  • template <>
    char* create<char, char>(int n)
    {
        return (char*)"HI";
    }
    

    And

    template <>
    const char* create<const char*, int>(int n)
    {
       return "Hi";
    }
    

    Are not template specializations: the former doesn't have a conforming argument and the later a conforming return type.

    template<>
    char* create<char, char>(char n)  // char n instead of int n
    {
        return (char*)"HI";
    }
    

    Here's a possible template specialization:

    template <>
    const char** create<const char*, int>(int n) // const char** instead of const char*
    {
        static const char* test="Hi";
        return &test;
    }