簡體   English   中英

類型別名和具有函數數據類型的別名模板

[英]Type alias and alias template with function datatype

template<typename R, typename... Types>
using Function = R(*)(Types...);

我在dev.to上看到了這條線

這種類型別名聲明R(*)(Types...)在我看來很奇怪,因為沒有函數名指針。

這是什么?如何實現此模板?

這種類型別名聲明R(*)(Types...)在我看來很奇怪,因為沒有函數名指針。

沒有名稱,因為它應該是一種類型。 舉一個簡單的例子:

using IPtr = int*;

RHS只是一種類型。 使用沒有意義

using IPtr = int* x;

這是什么?如何實現此模板?

它允許使用簡單直觀的語法聲明和定義函數指針。

您可以使用

int foo(double) { ... }
int bar(double) { ... }

Function<int, double> ptr = &foo;

// Use ptr

// Change where ptr points to

ptr = &bar;

// Use ptr more

我在https://en.cppreference.com/w/cpp/language/type_alias上找到了示例用法

// type alias, identical to
// typedef void (*func)(int, int);
using func = void (*) (int, int);
// the name 'func' now denotes a pointer to function:
void example(int, int) {}
func f = example;

這行是針對實際問題的實現;

template<typename R, typename... Types>
using Function = R(*)(Types...);
bool example(int&a){
    cout<< a;
    return false;
}
int main()
{
    int a  = 8;
    Function<bool, int&> eFnc =  example; 
    eFnc(a);
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM