获取“非法使用显式模板参数"对类方法进行指针部分特化时 [英] Getting "illegal use of explicit template arguments" when doing a pointer partial specialization for a class method

查看:20
本文介绍了获取“非法使用显式模板参数"对类方法进行指针部分特化时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我在部分专业化方面遇到了问题.我想要做的是有一个具有模板成员函数的类,该函数将把给定的值解释为用户指定的值.例如,类名是 Value,这是我想要做的一个片段:

Hello I'm having problems with partial specialization. What I want to do is have a class that has a template member function that will interpret a given value to one specified by the user. For instance the class name is Value and here is a snippet of what I want to do:

int *ptr1 = new int;
*ptr1 = 10;
Value val1 = ptr1;
int *ptr2 = val1.getValue<int*>();

Value val2 = 1;
int testVal = val2.getValue<int>();

这是我如何实现这样的类:

Here is how I implemented such class:

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':非法使用显式模板论据

error C2768: 'Value::getValue' : illegal use of explicit template arguments

基本上它抱怨代码的指针模板部分:

Basically its complaining about the pointer template part of the code:

template<typename T>
T* Value::getValue<T*>() {
    return reinterpret_cast<T*>(val1);
}

我知道这个问题可以用一个简单的联合来实现,但这段代码是一个更大代码的精简版.

I know this problem can be implemented with a simple union, But this code is a stripped down version of a bigger code.

有人知道可能是什么问题吗?我想要做的是将使用指针时的一个代码和不使用指针时的其他代码分开.我真的被困住了,我总是调查而不是询问,但我没有找到任何关于它的好信息.

Does someone know what the problem could be? What I would like to do is separate one code for when using pointers and other for when not using pointers . I'm really stuck and I always investigate instead of asking, but I haven't found any good info about it.

推荐答案

函数模板不能部分专门化,但大多数时候,您可以使用委托到类的技巧.在你的例子中,它会是这样的:

Function templates cannot be partially specialised, but most of the time, you can use the delegate-to-class trick. In you example it would be like this:

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);
  }
};

这篇关于获取“非法使用显式模板参数"对类方法进行指针部分特化时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆