如何更改模板实例化的外观,如std::函数中所示

How to change the look of an template instantiation like in std::function

本文关键字:函数 std 外观 何更改 实例化      更新时间:2023-10-16

创建一个std::function对象,如下所示:

std::function<int(int)> f = ...

由于<int(int)>不是我通常从模板中知道的,我想知道如何在自己的课堂上做这样的事情?比如我们可以在map<std::string -> int>这样的地图模板中使用吗?

模板参数是一个类型参数。像所有类型模板参数一样。因此,您将无法创建像您所说的地图示例那样的新语法。

std::function专门用于从作为类型发送的签名中提取参数。

以这个代码为例:

template<typename>
struct MyFunction;
template<typename R, typename... Args>
struct MyFunction<R(Args...)> {
    // do whatever you want
};

像这样的类型也可以别名:

using myFunctionType = int(double);
void doThings(myFunctionType* f) {
    // the type of f is int(*)(double), a function pointer.
}

或者您可以使用std::remove_pointer:提取此类型

// the following line is equivalent to using myFunctionType = int(double);
using myFunctionType = std::remove_pointer<int(*)(double)>::type;

所以基本上,类型int(double)是一种函数类型,通常与指针一起使用。在这种情况下,我们的类型是一个返回int并将double作为参数的函数类型。这里没有神奇的语法。

我认为您正在寻找的语法是不可能的。

std::function的工作原理如下:

template < typename Sig > struct function;
template < typename R, typename ... Params >
struct function<R(Params...)>
{
    // stuff and more stuff
};

签名是类型。然后,如上所述,进行部分专门化,以获得底层类型。。。比如返回类型和参数类型。

但是,您不能只是将任意语法添加到模板中并期望它能够工作。语言必须支持它,就像在签名的情况下一样。

相关文章: