我正在嘗試撰寫一個型別特征來檢查存盤在元組中的型別是否與給定可呼叫物件的引數兼容。
目前,我有“幾乎可以作業”的代碼,如下所示。但是,靜態斷言在最后一條陳述句中失敗,帶有一個需要參考引數(例如)的可呼叫物件[](int&, std::string&){},我真的不明白它為什么會失敗。一個人如何寫出同樣適用于這種型別的特征?
#include <type_traits>
#include <tuple>
#include <string>
template<typename, typename>
struct is_callable_with_tuple: std::false_type {};
template<typename Func, template<typename...> class Tuple, typename... Args>
struct is_callable_with_tuple<Func, Tuple<Args...>>: std::is_invocable<Func, Args...> {};
template<typename Func, typename Args>
constexpr bool is_callable_with_tuple_v = is_callable_with_tuple<Func, Args>::value;
int main() {
static_assert(is_callable_with_tuple_v<decltype([](int, std::string){}), std::tuple<int, std::string>>); // OK
static_assert(is_callable_with_tuple_v<decltype([](const int&, const std::string&){}), std::tuple<int, std::string>>); // OK
static_assert(is_callable_with_tuple_v<decltype([](int&, std::string&){}), std::tuple<int, std::string>>); // Fails
}
uj5u.com熱心網友回復:
您可能需要稍微修改您的特征:
template<typename Func,
template<typename...> class Tuple,
typename... Args>
struct is_callable_with_tuple<Func, Tuple<Args...>>:
std::is_invocable<Func, Args&...> {}; // <--- note &
與否,取決于您打算如何使用它。如果您的元組始終是左值,則可能沒問題。如果不是,那么您可能希望將其專門用于左值參考元組型別:
template<typename Func,
template<typename...> class Tuple,
typename... Args>
struct is_callable_with_tuple<Func, Tuple<Args...>&>: // <--- note & here
std::is_invocable<Func, Args&...> {}; // <--- and also here
template<typename Func,
template<typename...> class Tuple,
typename... Args>
struct is_callable_with_tuple<Func, Tuple<Args...>>: // <--- note NO & here
std::is_invocable<Func, Args...> {}; // <--- and also here
并像這樣使用它:
is_callable_with_tuple<decltype(myfunc), decltype((mytuple))> // note double parentheses
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/467046.html
下一篇:每種型別的模板虛方法
