在编译时仅接受特定的整数

诸如Allocator之类的一些命名要求希望您实现通用的方法,例如Allocator::allocate(int n)。对于我的特定情况,我只想实现参数n=1,如果可能,我会在编译时失败(如果提供了其他整数)。

到目前为止,我还没有找到任何可靠的解决方案。我只关心GCC和Clang。

  • 这在GCC中可以正常工作,但在Clang(Godbolt)中却不能:

    struct OneAndOnlyOne {
        constexpr OneAndOnlyOne(int v) noexcept {
            // static link-time error in Clang for any value of v unless -O2 is supplied:
            if (v != 1) _you_must_supply_a_one();
        }
    private:
        void _you_must_supply_a_one();
    };
    
  • assert使它成为运行时问题(Godbolt):

    struct OneAndOnlyOne {
        constexpr OneAndOnlyOne(int v) noexcept {
            // fails only at runtime:
            assert(v == 1);
            (void) v;
        }
    };
    
  • static_assert不起作用,或者:({Godbolt):

    struct OneAndOnlyOne {
        constexpr OneAndOnlyOne(int v) noexcept {
            // "error: 'v' is not a constant expression"
            static_assert(v == 1);
        }
    };
    
  • 似乎没有技巧将参数转换为模板参数(Godbolt):

    template <int> struct FailUnlessOne;
    template <> struct FailUnlessOne <1> {};
    
    struct OneAndOnlyOne {
        constexpr OneAndOnlyOne(int v) noexcept {
            // "error: 'v' is not a constant expression"
            constexpr FailUnlessOne<v> test;
            (void) test;
        }
    };
    

是否有我忽略的东西,还是根本无法在编译时测试参数?

gdfg3ggf 回答:在编译时仅接受特定的整数

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3150293.html

大家都在问