結果我有constexpr函數計算佔位符https://godbolt.org/g/JcxSiu的數量,編譯時間檢查的sizeof ...(參數)與從constexpr功能
e.g: 「Hello %1
」 返回1
和 「Hello %1, time is %2
」 返回2
。
然後,我想作出一個函數,如果參數的數量不等於佔位符的數量,它不會編譯。
template <typename... Args>
inline std::string make(const char* text, Args&&... args) {
constexpr static unsigned count = sizeof...(args);
// TODO how to compile time check if count == count_placeholders(text)
// constexpr static auto np = count_placeholders(text);
//static_assert(count == np;, "Wrong number of arguments in make");
return std::to_string(count);
};
使 make("Hello %1", "World");
編譯和
make("Hello %1 %2", "World");
或make("Hello %1", "World", "John");
沒有。
我認爲這是可以做到的,我只是不知道如何。也許一些模板magick :)
編輯
我幾乎得到了我想要的東西。 https://godbolt.org/g/Y3q2f8
現在以調試模式中止。編譯時錯誤是可能的?
這是**沒有答案**,因爲它使用GNU擴展buf,如果它不打擾你可以使用[字符串文字模板](https://wandbox.org/permlink/bSLW5DNEX4gNuDyw)。這將適用於gcc和clang,但可能不適用於任何其他編譯器...... –
這可能不是一個可以接受的答案,但這裏是使用Boost.Metaparse宏的解決方案。 [實施例](https://godbolt.org/g/tZYzyH)。 – llonesmiz