[英]C++ Function full specialization giving error
I have the below code to understand function full specialization concept:我有以下代码来理解 function 全专业化概念:
//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:上面的代码可以按预期正常编译和执行,但是当我将完整的专业化 function 签名更改为其他内容时:
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?为什么代码会报告错误以及如何解决?
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.