如何更改模板实例化的外观,如std::函数中所示
How to change the look of an template instantiation like in std::function
创建一个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
};
签名是类型。然后,如上所述,进行部分专门化,以获得底层类型。。。比如返回类型和参数类型。
但是,您不能只是将任意语法添加到模板中并期望它能够工作。语言必须支持它,就像在签名的情况下一样。
相关文章:
- 无法引用该函数" std:: variant <_Types...> operator =",因为此函数已被删除
- 错误:使用已删除的函数"std::unique_ptr<...>
- 我有模板功能.通过使用函数std::for_each,用这个容器中的最大数字替换每个正数
- 如何使用函数std::min()来计算最小值
- 删除了 g++ 在 linux 中basic_stringstream函数 std
- 如何在 c++ 中使用返回类型导出函数 std::map
- 错误:使用已删除的函数"std::atomic<_Tp>::atomic() [_Tp = node]"
- 使用 SFINAE 检查函数 std::to_string 是否存在类型
- C++14 unique_ptr并使用已删除的函数'std::unique-ptr' unique_ptr错误
- 为什么函数 std::basic_streambuf::setg() 需要非常量 agruments
- C++将已删除的函数 std::unique_ptr 与基类一起使用
- 奇怪的错误:当没有真正创建指针时,使用已删除的函数'std::unique_ptr<_Tp,_Dp>::unique_ptr
- 通过模板构造函数(std ::功能和迷你案例)将构造函数触发
- 错误:使用已删除的函数"std::atomic<_Tp>::atomic()
- 错误:使用已删除的函数std::basic_ofstream(OpenCV和C++11)
- 类成员容器迭代器在成员函数std::find中不兼容,但为什么不兼容呢
- 没有构造函数 std::istream_iterator 的实例
- 错误:没有与参数列表匹配的重载函数"std::make_shared"实例
- 错误:使用已删除的函数"std::thread::thread(const std::thread&)"
- 不能在没有对象的情况下调用成员函数 std::string class::function()