Kun*_*shu 13 c++ syntax templates template-specialization
你好,我有部分专业化的问题.我想要做的是拥有一个具有模板成员函数的类,该函数将给定值解释为用户指定的值.例如,类名是Value,这是我想要做的片段:
int *ptr1 = new int;
*ptr1 = 10;
Value val1 = ptr1;
int *ptr2 = val1.getValue<int*>();
Value val2 = 1;
int testVal = val2.getValue<int>();
Run Code Online (Sandbox Code Playgroud)
以下是我实现此类的方法:
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;
}
Run Code Online (Sandbox Code Playgroud)
当我编译时,我收到以下错误:
错误C2768:'Value :: getValue':非法使用显式模板参数
基本上它抱怨代码的指针模板部分:
template<typename T>
T* Value::getValue<T*>() {
return reinterpret_cast<T*>(val1);
}
Run Code Online (Sandbox Code Playgroud)
我知道这个问题可以通过一个简单的联合来实现,但是这个代码是一个更大代码的精简版本.
有人知道问题可能是什么吗?我想要做的是在使用指针时分离一个代码,而在不使用指针时分开.我真的被卡住了,我总是调查而不是问,但我没有找到任何关于它的好信息.
Rei*_*ica 13
函数模板不能部分专门化,但大多数时候,您可以使用委托到类的技巧.在你的例子中,它将是这样的:
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);
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12457 次 |
| 最近记录: |