C 语法:所请求的从某些_type转换为非scalar_type
c++ syntax: error conversion from some_type to non-scalar_type requested
第1行引起error: conversion from ‘C<void()>’ to non-scalar type ‘C<void (*)()>’ requested
。我知道我可以将其写为第2行,但是如何使用make_class()
并将其分配给变量?
#include <iostream>
using namespace std;
template<class T> class C {
T f;
public:
C(T ff) : f(ff) {}
};
template<class Ft> C<Ft> make_class(const Ft& f)
{
return C<Ft>(f);
}
void f()
{
cout << "f()" << endl;
}
int main()
{
// C<void(*)()> v = make_class(f); // line 1
C<void(*)()> v(f); // line 2
return 0;
}
另一个问题来自此链接。该代码如下显示。如何理解第3行?
template <typename F>
struct foo {
F f;
void call() {
f();
}
};
void function() {
std::cout << "function called" << std::endl;
}
int main() {
foo<void(*)()> a = { function }; // line 3: { } is an array?
a.call();
}
谢谢。
函数类型和功能类型的指针是语言中的不同类型。虽然在大多数情况下,前者会腐烂到后者,但是当用作模板参数时,它们会生成两种无关类型(模板的不同实例化产生无关类型的类型)。推论类型是 const引用函数,而不是指向函数的指针。一个简单的解决方法是将const &
从函数签名中删除,这将迫使衰减到指针函数(您不能按值传递函数)。
关于第二个问题,称为汇总initialization ,实际上是对数组执行的相同初始化(数组是聚集的子集)。
相关文章:
- 将内存分配返回值强制转换为 TYPE 数组
- C++ 嵌套类模板 错误 C2440 '=':无法从'type'转换为'same type'
- 为什么指针没有隐式转换为 <type> const*const
- 从整数到枚举的首选转换样式 QEvent::Type
- c++ C2440 错误无法从"const BWAPI::UpgradeType"转换为"const BWAPI::Type *"
- C++ 错误 C2662 无法将"this"指针从"const Type"转换为"Type &"
- 错误 C2440: 'type cast':无法从 'bool' 转换为 'CString'
- 无法将参数 1 从"cli::interior_ptr<Type>"转换为"CvCapture **"
- 将 MSVS 2010 项目转换为 MSVS 2012 RC,但出现错误"The C++ standard doesn't provide a hash for this type"
- 专用转换函数导致"ambiguous default type conversion"错误 (c++)
- vector::p ush_back 从 const Type* 转换为 type*
- 可以安全地使用静态强制转换,为每个实例使用唯一的虚拟 int type() 来提高性能
- 无法将参数 1 从"cli::array<Type> ^"转换为"无符号短整型"
- 无法从 Type* 转换为 Type&&
- 没有匹配的操作数[template]/无法从Type const*转换为Type
- C++ std::映射分配错误:无法在赋值中将' type **'转换为'type *'
- 错误 C2440 '=' : 无法从 'cli::array ^'<Type> 转换为 'wchar_t'
- 将Type**转换为void*,然后再返回到Type*
- 将 std::vector<const Type*> 转换为 const std::vector<T, A> &Vec
- 函数将变量Type转换为Type*,导致C++错误