"could not convert template argument"到自己的类型
"could not convert template argument" to its own type
我正在尝试创建一个可以类型安全地封装任意类型的类型。我脑子里有个想法,从这个答案中可以做到: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
),因此不能是变量(或函数参数)。允许将指针作为模板参数,但是您可以提供给它的内容不多,因为它需要是一个编译时常量指针值(我能想到的唯一限定的是指向字符串文字的字符指针)。一般规则很简单:所有模板参数都必须在编译时知道,无论是类型还是值。这不包括函数参数或其他类型的运行时变量。
我希望我能提出一个替代方案来实现你想要的,但我根本无法理解你实际上想做什么。
相关文章:
- 您应该在什么时候创建自己的异常类型
- 设计自己的结果/两者之一:是否应该始终指定成功类型和错误类型
- 您自己的类型的结构化绑定,不是结构或元组(通过公共成员函数)
- 类模板,在定义中引用其自己的类型
- (如何)在提升几何中创建自己的多边形类型并与之一起使用multi_polygon类型?
- 返回自己的类型的模板类方法的正确签名
- 函数可以将指针返回其自己的类型
- 使用库时的标准 - 使用库的数据类型 VS 创建我自己的类型?
- 如何为自己的类型声明自定义char_traits<>?
- "could not convert template argument"到自己的类型
- C++ std::函数,返回它自己的类型(再次递归类型)
- Buit矩形(我自己的类型),不会随窗口调整大小
- Q与自己的类型工作进行比较
- C++:一个类可以有它自己的类型的对象吗?
- 模板类专用化以处理其自己的类型
- 类自己的类型的静态类成员
- 如何声明为属性,指针到自己的类型,使用模板
- 如何用自己的类型实例化超类模板
- 递归typedef函数定义:std::函数返回自己的类型
- 我可以添加自己的类型转换操作符,以便能够将c++对象转换为objective C吗?