![](/img/trans.png)
[英]How to initialize std::array<T, n> elegantly if T is not default constructible?
[英]How to test if an std::function<T> is constructible for template argument T
我目前正在編寫一個模板類,它接受一個Signature
模板參數並在內部存儲一個std :: function。
template <class Signature>
class Impl
{
std::function<Signature> f;
};
這似乎工作得很好,除非Signature
模板參數無效,編譯器在std :: function中失敗並出現一些模板實例化錯誤。
現在因為Impl
客戶端不需要知道Impl
的內部結構,所以最好將一些人類可讀的消息輸出給將使用Impl
表示Signature
參數無效的開發人員。
使用is_invocable
特征類,類似於:
static_assert(is_invocable<Signature>::value, "Template parameter Signature is invalid");
在嘗試寫這樣的特質課時,我想出了這個:
template <class Signature>
struct is_invocable : std::false_type
{};
template <class Signature>
struct is_invocable <std::function<Signature>> : std::true_type
{};
但是這似乎不起作用,因為is_invocable
不想檢查Signature
是否是std :: function,而是可以構造一個std::function<T>
其中T
是模板參數Signature
。
怎么可能寫一個is_invocable
類?
注意:c ++ 17不可用。
正如StoryTeller在評論中建議的那樣,你想要std::is_function
,因為傳遞給std::function
的模板參數必須是簽名 。
template <class Signature>
struct Impl
{
static_assert(std::is_function<Signature>::value, "");
std::function<Signature> f;
};
std::function
將檢查其函數對象是否可以使用Signature
進行調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.