【问题标题】:c++ syntax: error conversion from some_type to non-scalar_type requestedc++ 语法:从 some_type 到 non-scalar_type 请求的错误转换
【发布时间】:2014-01-20 22:45:30
【问题描述】:

第 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;
}

另一个问题来自这个link。代码如下所示。如何理解第 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();
}

谢谢。

【问题讨论】:

    标签: c++


    【解决方案1】:

    函数类型和指向函数类型的指针在语言中是不同的类型。虽然在大多数情况下前者会衰减为后者,但当用作模板参数时,它们会生成两种不相关的类型(模板的不同实例化会产生不相关的类型)。 推导出的类型是对函数的常量引用,而不是指向函数的指针。一个简单的解决方法是从函数签名中删除const &amp;,这将强制衰减到指向函数的指针(您不能按值传递函数)。

    关于第二个问题,即所谓的聚合初始化,这实际上与对数组执行的初始化相同(数组是聚合的子集)。

    【讨论】:

      猜你喜欢
      • 2011-02-10
      • 1970-01-01
      • 2019-05-19
      • 2017-04-25
      • 2019-01-15
      • 1970-01-01
      • 1970-01-01
      • 2016-07-01
      相关资源
      最近更新 更多