C 语法:所请求的从某些_type转换为非scalar_type

c++ syntax: error conversion from some_type to non-scalar_type requested

本文关键字:type 转换 scalar 语法 请求      更新时间:2023-10-16

第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 ,实际上是对数组执行的相同初始化(数组是聚集的子集)。