[英]How to check at compile-time if a function that can be called with a specific set of arguments exists?
[英]How can I check if a templated method was called at compile-time?
我正在編寫一個實體實體組件系統游戲引擎 。 作為其中的一部分,我編寫了一個Manager
類,它將注冊各種IBase
實現,稍后,允許我實例化這些實現。 請參閱下面的示例,了解我希望如何使用它。
class Manager{
public:
template<class T>
void registerDerived()
{ /*Register a Derived with the Manager*/ };
template<class T>
T createDerived()
{ /*if T is not registered, throw an error*/
return T();};
};
struct IBase{
};
struct Derived1 : public IBase{
};
struct Derived2 : public IBase{
};
如注釋中所述,我在template<class T>Manager::createDerived()
有代碼,它檢查是否已使用template<class T>Manager::registerDerived()
注冊了Base
的特定實現,如果是尚未注冊它會拋出錯誤。 這個檢查是微不足道的,並且不在代碼示例中以保持簡單。
這是我的問題:是否可以將此檢查移至編譯時,而不是等到運行時? 似乎在運行時應該有足夠的信息來做出這個決定。
到目前為止,我已經探索/閱讀了SFINAE,這似乎是采取的方法,但我無法弄清楚如何使這些習語在這種特定情況下起作用。 這個鏈接很好地概述了基本的SFINAE習語, 這個SO問題提供了一些很好的代碼片段,最后這篇博文似乎幾乎解決了我的確切情況。
以下是我嘗試實現這些鏈接中的信息的完整示例:
#include <iostream>
class Manager{
public:
template<class T>
void registerDerived()
{ /*Register a Derived with the Manager*/ }
template<class T>
T createDerived()
{ /*if T is not registered, throw an error*/
return T();}
};
struct IBase{
};
struct Derived1 : public IBase{
};
struct Derived2 : public IBase{
};
template<typename T>
struct hasRegisterDerivedMethod{
template <class, class> class checker;
template <typename C>
static std::true_type test(checker<C, decltype(&Manager::template registerDerived<T>)> *);
template <typename C>
static std::false_type test(...);
typedef decltype(test<T>(nullptr)) type;
static const bool value = std::is_same<std::true_type, decltype(test<T>(nullptr))>::value;
};
int main(){
Manager myManager;
myManager.registerDerived<Derived1>();
// whoops, forgot to register Derived2!
Derived1 d1 = myManager.createDerived<Derived1>(); // compiles fine, runs fine. This is expected.
Derived2 d2 = myManager.createDerived<Derived2>(); // compiles fine, fails at runtime (due to check in createDerived)
std::cout << std::boolalpha;
// expect true, actual true
std::cout << "Derived1 check = " << hasRegisterDerivedMethod<Derived1>::value << std::endl;
// expect false, actual true
std::cout << "Derived2 check = " << hasRegisterDerivedMethod<Derived2>::value << std::endl;
return 0;
}
**
如何修改上面的代碼以產生編譯時錯誤(可能使用static_assert
)而不是等到運行時才能檢測到錯誤?
**
恕我直言,你有一個設計問題。 registerDerived<Derived>()
是調用createDerived<Derived>()
的先決條件的事實應該用代碼表示(不僅僅是在文檔中),這樣就不可能進行未注冊的創建。
實現這一目標的一種方法是通過注冊時發布的注冊文件。 例如
#include <typeinfo>
#include <typeindex>
#include <unordered_set>
struct Manager {
// serves as registration document
template<typename T>
class ticket { friend struct Manager; };
// use SFINAE to restrict T to a derived class (assumed C++14)
template<typename T>
std::enable_if_t<std::is_base_of<Manager,T>::value, ticket<T> >
registerDerived()
{
registeredTypes.insert(std::type_index(typeid(T)));
return {};
}
template<typename T, typename... Args>
T createDerived(ticket<T>, Args&&...args)
{
return T(std::forward<Args>(args)...);
}
private:
std::unordered_set<std::type_index> registeredTypes;
};
struct Derived1 : Manager {};
struct Derived2 : Manager { Derived2(int); }
int main() {
Manager manager;
auto t1 = manager.registerDerived<Derived1>();
auto t2 = manager.registerDerived<Derived2>();
auto x1 = manager.createDerived(t1);
auto x2 = manager.createDerived(t2,7);
}
請注意,對象t
可能已經過優化。
當然,這段代碼與您的代碼不同,因為它需要為任何創建攜帶ticket<Derived>
。 然而,在這個簡單的例子中,注冊后跟創建的概念是不明智的,因為下面的代碼總是有效並且沒有事先注冊(參見我在評論中的問題):
template<typename T, typename...Args>
T Manager::create(Args&&..args)
{
return createDerived(register<T>(),std::forward<Args>(args)...);
}
如果每次查看注冊比我的簡單示例更昂貴,那么您可以在嘗試之前檢查(使用上面的unordered_set<type_index>
)是否注冊了Derived
類型。
我認為這不可能以便攜/可靠的方式進行。
如果您對編譯時只對注冊感興趣,我建議將Manager
作為模板類,其中模板參數是注冊類型。
我的意思是......如果你寫一個自定義類型特征如下
template <typename, typename ...>
struct typeInList;
template <typename T0, typename T1, typename ... Ts>
struct typeInList<T0, T1, Ts...> : public typeInList<T0, Ts...>
{ };
template <typename T0, typename ... Ts>
struct typeInList<T0, T0, Ts...> : public std::true_type
{ using type = T0; };
template <typename T0>
struct typeInList<T0> : public std::false_type
{ };
template <typename ... Ts>
using typeInList_t = typename typeInList<Ts...>::type;
或者(由Deduplicator建議(謝謝!))以更緊湊的方式
// ground case: in charge only when `typename...` variadic list
// is empy; other cases covered by specializations
template <typename, typename...>
struct typeInList : public std::false_type
{ };
template <typename T0, typename T1, typename ... Ts>
struct typeInList<T0, T1, Ts...> : public typeInList<T0, Ts...>
{ };
template <typename T0, typename ... Ts>
struct typeInList<T0, T0, Ts...> : public std::true_type
{ using type = T0; };
template <typename ... Ts>
using typeInList_t = typename typeInList<Ts...>::type;
您可以使用它來SFINAE啟用/禁用createDerived()
,如下所示
template <typename ... Ts>
struct Manager
{
template <typename T>
typeInList_t<T, Ts...> createDerived ()
{ return T(); }
};
和hasRegisterDerivedMethod
可以寫成如下
template <typename, typename>
struct hasRegisterDerivedMethod;
template <typename ... Ts, typename T>
struct hasRegisterDerivedMethod<Manager<Ts...>, T>
: public typeInList<T, Ts...>
{ };
不幸的是,這適用於編譯時但不是運行時,因此,如果您需要一個兼容編譯時和運行時的解決方案,此解決方案不適合您。
以下是一個完整的工作示例
#include <iostream>
template <typename, typename ...>
struct typeInList;
template <typename T0, typename T1, typename ... Ts>
struct typeInList<T0, T1, Ts...> : public typeInList<T0, Ts...>
{ };
template <typename T0, typename ... Ts>
struct typeInList<T0, T0, Ts...> : public std::true_type
{ using type = T0; };
template <typename T0>
struct typeInList<T0> : public std::false_type
{ };
template <typename ... Ts>
using typeInList_t = typename typeInList<Ts...>::type;
template <typename ... Ts>
struct Manager
{
template <typename T>
typeInList_t<T, Ts...> createDerived ()
{ return T(); }
};
struct IBase { };
struct Derived1 : public IBase{ };
struct Derived2 : public IBase{ };
template <typename, typename>
struct hasRegisterDerivedMethod;
template <typename ... Ts, typename T>
struct hasRegisterDerivedMethod<Manager<Ts...>, T>
: public typeInList<T, Ts...>
{ };
int main ()
{
Manager<Derived1> myManager;
// whoops, forgot to register Derived2!
Derived1 d1 = myManager.createDerived<Derived1>();
//Derived2 d2 = myManager.createDerived<Derived2>(); // compilation error!
std::cout << std::boolalpha;
std::cout << "Derived1 check = "
<< hasRegisterDerivedMethod<decltype(myManager), Derived1>::value
<< std::endl; // print true
std::cout << "Derived2 check = "
<< hasRegisterDerivedMethod<decltype(myManager), Derived2>::value
<< std::endl; // print false
}
關閉主題:而不是
static const bool value = std::is_same<std::true_type, decltype(test<T>(nullptr))>::value;
你可以寫
static constexpr bool value { type::value };
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.