对于静态const getter,内联vs constexpr?

Vin*_*ent 16 c++ inline constexpr c++11

在下面的代码中,哪个函数可以为外部使用提供最佳优化,为什么?C++ 2011中是否允许"版本4"?

template<unsigned int TDIM> class MyClass 
{
    public:
        static inline unsigned int size()           {return _size;} // Version 1
        static inline const unsigned int size()     {return _size;} // Version 2
        static constexpr unsigned int size()        {return _size;} // Version 3
        static inline constexpr unsigned int size() {return _size;} // Version 4
    protected:
        static const unsigned int _size = TDIM*3;
};
Run Code Online (Sandbox Code Playgroud)

非常感谢你.

How*_*ant 21

我相信代码<random>设置了一个很好的例子,但也不需要盲目跟随.在<random>你看到这两种风格:

template<unsigned int TDIM> class MyClass 
{
    public:
        static constexpr unsigned int size() {return _size;}  // 1
        static constexpr unsigned int dim = TDIM;             // 2
    private:
        static const unsigned int _size = TDIM*3;
};
Run Code Online (Sandbox Code Playgroud)

1和2之间的选择主要是风格.当它们以需要编译时结果的方式使用时,它们在编译时都被解析.你想要你的客户打字()吗?是否需要使用一种风格或另一种风格的通用代码?满足通用代码的要求是关键.

使用inline关键字对此没有影响.我认为它过于冗长,但它没有任何危害,如果你使用它没有任何影响.

添加const到返回类型不会对此产生任何影响.我认为它过于冗长,但它没有任何危害,如果你使用它没有任何影响.

如果使用函数样式,但不要使用constexpr:

    static unsigned int size() {return _size;}
Run Code Online (Sandbox Code Playgroud)

那么这个函数不能在编译时调用,因此不能在需要编译时常量的上下文中使用.如果您的应用程序或客户不需要此类功能,则不会对您造成任何伤害.但是imho,如果你已经进入constexpr工具箱,这是使用它的最佳地点.如果你做未来的客户可以做这样的事情:

template <unsigned N> struct B {};
constexpr auto myclass = MyClass<3>();
// ...
// lots of code here
// ...
B<myclass.size()> b;
Run Code Online (Sandbox Code Playgroud)

这两个是等价的:

        static constexpr unsigned int dim = TDIM;        // 2
        static const unsigned int dim = TDIM;            // 3
Run Code Online (Sandbox Code Playgroud)

但只是因为涉及的类型是不可或缺的.如果类型不是整数,那么你必须使用constexpr,类型必须有一个constexpr构造函数:

class A
{
    unsigned _i;
public:
    constexpr A(unsigned i) : _i(i) {}
};

template<unsigned int TDIM> class MyClass 
{
    public:
        static constexpr unsigned int size() {return _size;}
        static constexpr unsigned int dim = TDIM;
        static constexpr A a = A(dim);
    private:
        static const unsigned int _size = TDIM*3;
};
Run Code Online (Sandbox Code Playgroud)

这里的每个人,包括我自己,都在学习如何使用constexpr.所以在问题上+1.