[英]Why use decltype on a template argument?
在https://github.com/stlab/libraries/blob/main/stlab/concurrency/main_executor.hpp ,我讀到
struct main_executor_type {
using result_type = void;
template <typename F>
void operator()(F f) const {
using f_t = decltype(f);
dispatch_async_f(dispatch_get_main_queue(), new f_t(std::move(f)), [](void* f_) {
auto f = static_cast<f_t*>(f_);
(*f)();
delete f;
});
}
};
decltype(f)
有什么意義,為什么不簡單地使用F
?
這取決於,因為在某些情況下會導致F
和decltype(f)
之間產生不同的效果。
例如,可以將F
顯式指定為數組或函數類型,並將函數參數的類型調整為指針。 然后F
和decltype(f)
給出不同的結果。
template <typename F> // suppose F is specified as array of T or function type F
void operator()(F f) const {
using f_t = decltype(f); // f_t will be pointer to T or pointer to F
...
}
對於這個特定的代碼示例,我看不到任何有用的場景(如果我錯了,請糾正我),但如果參數被聲明為 cv 限定,例如const F f
,它看起來會有所不同。 然后, using f_t = decltype(f);
將評估為const F
,同時using f_t = F;
將刪除 cv 限定符並評估為F
。
為了更好地理解,請考慮以下簡約示例:
#include <type_traits>
template <typename T>
void foo(const T t) {
using X = decltype(t);
static_assert(std::is_const_v<X>); // will fail if using X = T;
}
int main() {
const int a = 123;
foo(a); // T will be deduced to int, i.e. cv qualifiers are removed
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.