在对类方法执行指针部分专用化时获取"illegal use of explicit template arguments"
Getting "illegal use of explicit template arguments" when doing a pointer partial specialization for a class method
你好,我有部分专业化的问题。我想做的是有一个类,它有一个模板成员函数,将给定的值解释为用户指定的值。例如,类名是Value
,下面是我要做的代码片段:
int *ptr1 = new int;
*ptr1 = 10;
Value val1 = ptr1;
int *ptr2 = val1.getValue<int*>();
Value val2 = 1;
int testVal = val2.getValue<int>();
下面是我如何实现这样的类:
struct Value {
Value(void *p) : val1(p){}
Value(int i) : val2(i){}
template<typename T>
T getValue();
void *val1;
int val2;
};
template<typename T>
T* Value::getValue<T*>() {
return reinterpret_cast<T*>(val1);
}
template<>
int Value::getValue<int>() {
return val2;
}
当我编译时,我得到以下错误:
错误C2768: 'Value::getValue':非法使用显式模板参数
基本上是在抱怨代码的指针模板部分:
template<typename T>
T* Value::getValue<T*>() {
return reinterpret_cast<T*>(val1);
}
我知道这个问题可以用一个简单的联合来实现,但这段代码是一个更大的代码的剥离版本。
有人知道是什么问题吗?我想做的是分开一个代码当使用指针和其他不使用指针时。我真的被困住了,我总是调查而不是询问,但我还没有找到任何关于它的好信息。
函数模板不能部分专门化,但大多数情况下,您可以使用委托到类的技巧。在您的示例中,它将像这样:
struct Value {
template<typename T>
T getValue() {
return Impl_getValue<T>::call(*this);
}
};
template <typename T>
struct Impl_getValue
{
static T call(Value &v) {
//primary template implementation
}
};
template <typename T>
struct Impl_getValue<T*>
{
static T* call(Value &v) {
return reinterpret_cast<T*>(v.val1);
}
};
相关文章:
- 如何处理 c++ 中类实现中的"invalid use of non-static data member"?
- C++ "error: invalid use of void expression"
- 我看到"use of undeclared identifier"错误,有人可以告诉我如何解决它吗?
- 收到错误"invalid use of non-static data member 'stu::n' "
- 模式"allocate memory or use existing data"
- C++ "error: use of overloaded operator '*' is ambiguous"似乎只有一场比赛
- Is it good to use SDL_PIXELFORMAT_UNKNOWN?
- C++ "Invalid use of 'this' in non-member function" ,
- std::launder use cases in C++20
- 继承类时"invalid use of incomplete type ‘class tree_node_t’"
- "reserved for any use"的含义是什么?
- C++14 遇到奇怪的"use of deleted function"错误
- C++ 中的 use 函数是什么?
- 出现这种错误的原因是什么"invalid use of non-static data member "
- 如何解决g++问题"internal compiler error: Illegal instruction min() _GLIBCXX_USE_NOEXCEPT { return __FLT_MI
- 模板类和'invalid use of incomplete type'错误
- 为什么"non-standard syntax; use '&' to create a pointer to member"在 CTOR 中使用线程?
- "error: C2275: 'QMouseEvent' : illegal use of this type as an expression"
- 在对类方法执行指针部分专用化时获取"illegal use of explicit template arguments"
- 简单的模板化函数,用于转换 std::vectors - "illegal use of this type as an expression"