constexpr

    0熱度

    1回答

    我有這樣的源代碼,有一個枚舉,我希望可以評估爲constexpr,但編譯器給我一個錯誤,它不是。爲什麼? 如果EventOrder是enum或enum class,則無關緊要。 #include <limits> #include <type_traits> enum class EventOrder { Last = 1'000'000, Default = 0,

    10熱度

    2回答

    內是否有可能有這樣的事情在C++: struct Foo { int x; constexpr Foo(int x) : x(x) {} static constexpr Foo table[] = { Foo(0), Foo(1), Foo(2), }; }; 我嘗試了好幾種組合,但沒有工作。如果ta

    7熱度

    2回答

    我正在閱讀關於SO的this問題。 問題本身並不是那麼有趣,但我想知道它是否存在以及如何實現編譯時解決方案。 關於第一個序列: [1, 2, 4, 5, 7, 8, 10, 11, 13, 14, ...] 通過歸納: 除了那些可以由3 序列劃分應該像所有的數字,我找到了該序列的數學公式: f(0) = 0; f(x > 0) = floor[(3x - 1)/2]; 因此,我已經實現了

    1熱度

    2回答

    我可以使用模板和刪除功能來防止調用具有字符或浮點變量的階乘,如下所示。如何爲具有負面參數的階乘編寫刪除函數? template <typename T> constexpr T factorial(T n) { return (n == 1 || n == 0) ? 1 : (n * factorial(n - 1)); } constexpr float factorial(

    0熱度

    3回答

    #include <array> #include <tuple> typedef std::tuple<const int> TupleType; constexpr std::array<const int, 2> a = {1, 2}; constexpr void foo() { for (std::size_t i = 0; i < a.size(); ++i)

    3熱度

    1回答

    下面的代碼編譯失敗: // template<class> struct S { int g() const { return 0; } constexpr int f() const { return g(); } }; int main() { S /*<int>*/ s; auto z = s.f

    1熱度

    1回答

    爲什麼是constexpr部分?我認爲這就像內聯。 中f的實際類型是什麼? 這工作: void f() { auto f = []() { return 42; }; auto p = f; static_assert(std::is_same_v<decltype(f), decltype(p)>); } 但這並不: void g() { co

    7熱度

    1回答

    嘗試針對該類的特定構造函數的特定類類型嘗試別名make_shared。我最好的嘗試: class foo { public: foo(int x) : y(x) {} int y; }; constexpr auto newfoo = static_cast<std::shared_ptr<foo>(*)(int)>(std::make_shared<foo>); 產量: error: in

    16熱度

    2回答

    雖然我用這樣的代碼之前,並且很顯然,編譯器有足夠的信息來工作,我真的不明白爲什麼這個編譯: template <class T, class I> auto foo(const T& t, I i) { return std::get<i>(t); } int main() { std::cerr << foo(std::make_tuple(3,4), std::i

    7熱度

    1回答

    我知道模板函數在鏈接時不會遇到多重定義,就像在類中定義的成員函數一樣,默認情況下它們是內聯的。此外,constexpr對象具有內部鏈接,但模板變量具有外部鏈接(我的意思是在命名空間範圍內,在這兩種情況下都是C++ 14)。 怎麼辦? template<class T> constexpr T i_am_odr_safe{}; i_am_odr_safe在C++ 14中有外部或內部鏈接嗎?對於