为什么模板参数中不允许类类型对象?
Why class type object aren't allowed in template parameter?
以下内容不起作用:
// case one:
struct MyClass {
int x;
};
template <MyClass name>
void foo() {
}
但是如果我把它作为一个参考,它可以工作:
// case two:
struct MyClass {
int x;
};
template <MyClass &name>
void foo() {
}
我是否需要传递 MyClass 的常量对象才能在万一的情况下与类一起使用?
看起来您正在尝试专门化模板?
也许这就是你想要的?
template <typename T>
void foo(const T& param){
cout << reinterpret_cast<const int&>(param) << endl;
}
template <>
void foo(const MyClass& param) {
cout << param.x << endl;
}
int main() {
MyClass bar = {13};
foo(42L); // Outputs 42
foo(bar); // Outputs 13
return 0;
}
(请注意,reinterpret_cast
是高度可疑的,我只是在这里使用它作为一个例子。
相关文章:
- std::unordered_map 类型对象声明期间出现"field has incomplete type"错误
- C++ 多态模板类,模板类型对象的实例化
- 如何分配适合容纳 T 类型对象的缓冲区(可能过度对齐、可能有运算符 new 等)
- 如何构造一个 std::variant 类型对象,其自身 Templated 和构造函数转发参数
- C++:初始化指向具有不同类型对象的指针数组
- 在类 C++ 中构造的模板类型对象
- 如何将颁发者名称设置为x509_req类型对象
- 将任何数据类型/对象作为参数传递以确定其大小
- 将引用类型对象的数组从C#封送到C++
- <T> 从类型对象创建类型<T1>对象的构造函数
- C++是否有现有的方法来检查对象是否是派生类型对象
- C 模板:创建与现有对象相同的类型对象
- 链接列表中的虚函数 - 多种返回类型(对象)
- 没有适当操作员()的类型对象的呼叫
- 制作垫子类型对象的数组.输出窗口显示同一帧
- 抽象类型对象的分配
- 在std::list中就地创建自定义类型对象
- 接受泛型列表类型对象的参数
- C++-将模板类型对象强制转换为特定的数据类型
- 试图在C++中打印存储在类型对象数组中的信息