Typedef 期望在" "之前';'

Typedef expecting ';' before ""

本文关键字:期望 Typedef 之前      更新时间:2023-10-16

(不要因为使用std::auto_ptr<>而让我抓狂,这不是我的代码,它是自动生成的。我只是想和它连接。)

我有一个签名如下的函数:

std::auto_ptr<T> gFunction(const std::string&, int, const int&)

这个函数被重载了588次,所以将它赋值给boost::function是有歧义的。好的,我将重新定义它,然后赋值。

像这样键入很麻烦:

std::auto_ptr<T> (*func)(const std::string&, int, const int&) = &gFunction

我想typedef这个,所以我可以使用它在以下方式:

function_type func = &gFunction

所以我尝试键入pedef

typedef std::auto_ptr<T>(*funct)(const std::string&, int, const int&) function_type;

但是我的typedef返回的是error: expected ‘;’ before ‘function_type’

任何想法?我可能遗漏了一些简单的东西。

就这样做:

typedef std::auto_ptr<T>(*function_type)(const std::string&, int, const int&);

还请记住,自c++ 11以来,std::auto_ptr已被弃用。如果可以,您应该使用std::unique_ptr

在c++ 11中,您还可以使用std::add_pointer类型trait来添加指向函数类型的指针(如果这对您来说更直观):

#include <type_traits>
typedef typename std::add_pointer<
    std::shared_ptr<T>(const std::string&, int, const int&)
    >::type function_type;

另外,正如Mike Seymour在评论中提到的,您可以考虑将类型别名function_type定义为函数类型(正如其名称所暗示的那样),而不是使其成为函数指针类型(只需删除*即可)。

声明类型定义的正确语法应该模仿变量声明。在语法上,它们是相同的,除了你用'typedef'作为前缀。从语义上讲,声明的名称具有非常不同的目的(一个创建变量,一个创建类型)

就像您输入下面的语句来声明变量

一样
std::auto_ptr<T> (*func)(const std::string&, int, const int&);

你可以把它设为typedef只要在前面加一个"typedef"就行了

typedef std::auto_ptr<T> (*func)(const std::string&, int, const int&);