"could not convert template argument"到自己的类型

"could not convert template argument" to its own type

本文关键字:自己的 类型 argument template could not convert      更新时间:2023-10-16

我正在尝试创建一个可以类型安全地封装任意类型的类型。我脑子里有个想法,从这个答案中可以做到:5年后,还有比"最快的C++代表"更好的吗?到目前为止,我只成功地移动了问题,但我遇到了一个我找不到根源的错误。

编译器似乎告诉我它不能将值转换为值自己的类型,这让我觉得很奇怪。

我正在运行带有llvm-gcc 4.2(gcc 4.2.1前端)的Mac OS X 10.6。

欢迎提出如何摆脱空白*或将其移动到不那么重要的位置的建议,但这个问题并不是真的关于这个问题。

错误:

$ g++ main.cpp
main.cpp: In static member function ‘static Stamp StampFactory<T>::make(T*) [with T = int]’:
main.cpp:33:   instantiated from ‘Stamp makeStamp(T*) [with T = int]’
main.cpp:39:   instantiated from here
main.cpp:26: error: could not convert template argument ‘t’ to ‘int*’

代码:

typedef void (*VoidFunc)(void*);
struct Stamp
{
    Stamp(VoidFunc p)
    {
        this->press = p;
    }
    VoidFunc press;
};
template<typename T>
struct StampFactory
{
    template<T* rvalue>
    struct Pattern
    {
        void operator()(void* lvalue)
        {
            *dynamic_cast<T*>(lvalue) = *rvalue;
        }
    };
    static Stamp make(T* t)
    {
        return Stamp(Pattern<t>()); // 28
    }
};
template<typename T>
Stamp makeStamp(T* t)
{
    return StampFactory<T>::make(t); // 33
}
int main(int argc, char** argv)
{
    int i = 0;
    Stamp s = makeStamp(&i); //39
}

该错误是由于模板参数必须是编译时常量(或constexpr),因此不能是变量(或函数参数)。允许将指针作为模板参数,但是您可以提供给它的内容不多,因为它需要是一个编译时常量指针值(我能想到的唯一限定的是指向字符串文字的字符指针)。一般规则很简单:所有模板参数都必须在编译时知道,无论是类型还是值。这不包括函数参数或其他类型的运行时变量。

我希望我能提出一个替代方案来实现你想要的,但我根本无法理解你实际上想做什么。