當我使用一個引數(組件)創建模板函式時,有時會使用兩個(組件,游戲物件)創建模板函式。
template<typename Component, typename F>
static void CallFunction(GameObject gameObject, F func) {
// Note: UIFunction should has component as first param and/or gameObject second.
auto& component = gameObject.GetComponent<Component>();
constexpr std::size_t args = sizeof...(F);
if constexpr (args == 1)
func(component);
else
func(component, gameObject);
}
我嘗試使用constexpr std::size_t args = sizeof...(F);來獲取函式引數的大小并用一兩個引數呼叫它。但是當我嘗試使用它時,我得到:
C2780 'auto CallFunction::<lambda_06a5858866216a23f9192bc2da910cdc>::operator ()(_T1 &,_T2) const': expects 2 arguments - 1 provided.
如何正確執行此操作,因為我不是模板的忠實粉絲。
uj5u.com熱心網友回復:
我洗掉sizeof...(T)并std::is_invokable_v用于檢查是否可以使用某些計數和型別的引數呼叫 func。
template<typename Component, typename F>
static void CallFunction(GameObject gameObject, F func) {
// Note: UIFunction should has component as first param and/or gameObject second.
auto& component = gameObject.GetComponent<Component>();
if constexpr (std::is_invocable_v<F, Component>)
func(component);
if constexpr (std::is_invocable_v<F, Component, GameObject>)
func(component, gameObject);
}
uj5u.com熱心網友回復:
由于 C 17 型別特征可用于確定物件是否可呼叫并接受某些引數型別。小例子,根據需要改變它:
template<typename> inline constexpr bool wrong_func_v = false;
template<typename Component, typename F>
static void CallFunction(GameObject gameObject, F func)
{
auto& component = gameObject.GetComponent<Component>();
if constexpr (std::is_invocable_v<F, Component>)
func(component);
else if constexpr (std::is_invocable_v<F, Component, GameObject>)
func(component, gameObject);
else
static_assert(wrong_func_v<F>, "wrong param types/count");
}
然后我們可以使用這個模板:
CallFunction<SomeComponent>(gameObject, one_arg_func);
CallFunction<OrAnotherComponent>(gameObject, two_arg_func);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/412626.html
標籤:
