比方說,我有這樣定義的類FunctionWrapper
:防止隱式轉換,但允許列表初始化?
struct FunctionWrapper
{
FunctionWrapper(std::function<void()> f);
// ... plus other members irrelevant to the question
};
我想,以防止隱式轉換從std::function<void()>
到FunctionWrapper
,但允許使用大括號初始化語法(即使用列表初始化構建FunctionWrapper
只有一個參數)。換句話說,我想這樣:
void foo();
void wrap(FunctionWrapper);
wrap(foo); // (1) error
wrap({foo}); // (2) OK
wrap(FunctionWrapper{foo}); // (3) OK
有沒有辦法做到這一點?我定義上面的類的方式不是這樣的:這允許隱式轉換,所以(1)編譯。
如果我添加explicit
的構造器:
struct FunctionWrapper
{
explicit FunctionWrapper(std::function<void()> f);
// ... plus other members irrelevant to the question
};
它並沒有幫助,因爲這雲「過猶不及」,並禁止(2)和(1)。
有沒有辦法實現「中間地帶」,並有(2)編譯while(1)產生錯誤?
添加一個採用'std :: initializer_list'參數的顯式構造函數。 –
你可以使用initializer_list,但那麼你將只有運行時檢查參數的數量......也許模板接受常量數組和static_assert模板大小......但只是醜陋 – Hcorg
@Hcorg不會[this](http:///melpon.org/wandbox/permlink/0rFgVYD8XKYwVlC1)需要雙括號初始化? –