C++ C++;函数全特化给定错误
我有以下代码来理解函数完全专业化的概念:C++ C++;函数全特化给定错误,c++,templates,template-specialization,C++,Templates,Template Specialization,我有以下代码来理解函数完全专业化的概念: //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<
//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);
}
//函数完全专门化是合法的,但不是部分的
类包装器
{
公众:
void setValue(int x){}
};
模板
R*创建(T)
{
返回新的R(t);
}
模板
包装器*create(int n)//现在完全专用->合法。。。
{
包装器*w=新包装器();
w->setValue(n);
返回w;
}
//模板
//包装器*create(tn)//现在部分专用->非法。。。
//{
//包装器*w=新包装器();
//w->setValue(n);
//返回w;
//}
//T
int main()
{
创建(2);
创建(2);
}
上面的代码按照预期编译和执行得很好,但当我将完全专门化函数签名更改为其他内容时:
template <>
const char* create<const char*, int>(int n) // fully specialized now -> legal...
{
//Wrapper* w = new Wrapper();
//w->setValue(n);
//return w;
return "Hi";
}
模板
const char*create(int n)//现在完全专业化->合法化。。。
{
//包装器*w=新包装器();
//w->setValue(n);
//返回w;
返回“Hi”;
}
或
模板
char*create(int n)//现在完全专业化->合法化。。。
{
返回(字符*)“HI”;
}
错误:
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
显式专门化“const char*create(int)”不是函数模板专门化和重载的专门化
显式专门化“char*create(int)”不是函数模板专门化和重载的专门化
为什么代码会报告错误以及如何修复错误?模板
template <>
char* create<char, char>(int n)
{
return (char*)"HI";
}
字符*创建(int n)
{
返回(字符*)“HI”;
}
及
模板
常量字符*创建(整数n)
{
返回“Hi”;
}
不是模板专门化:前者没有一致性参数,后者有一致性返回类型
template<>
char* create<char, char>(char n) // char n instead of int n
{
return (char*)"HI";
}
模板
char*create(char n)//char n而不是int n
{
返回(字符*)“HI”;
}
及
模板
常量字符**创建(int n)//常量字符**而不是常量字符*
{
静态常量字符*test=“Hi”;
返回和测试;
}
是。您使用的编译器是什么?我怀疑它可能与未使用的参数有关,但我必须测试它。VisualC++ 2019 16.7.3与未使用的参数无关,而是与不遵守模板规范的函数有关:
template <>
const char* create<const char*, int>(int n)
{
return "Hi";
}
template<>
char* create<char, char>(char n) // char n instead of int n
{
return (char*)"HI";
}
template <>
const char** create<const char*, int>(int n) // const char** instead of const char*
{
static const char* test="Hi";
return &test;
}