简化模板类的静态const成员定义

时间:2019-07-24 20:57:30

标签: c++ c++11

我试图清晰地定义一个类的一组静态const成员变量,但是我觉得我的代码被样板语法所淹没。

这是一个例子:

template <typename InputT, typename OutputT>
class MyClassWithALongName {
    public:
        static const std::string kParameterOne;
        static const std::string kParameterTwo;
        static const std::string kParameterThree;
};

template <typename InputT, typename OutputT>
const std::string MyClassWithALongName<InputT, OutputT>::kParameterOne = "The quick brown fox";
template <typename InputT, typename OutputT>
const std::string MyClassWithALongName<InputT, OutputT>::kParameterTwo = " jumps over";
template <typename InputT, typename OutputT>
const std::string MyClassWithALongName<InputT, OutputT>::kParameterThree = " the lazy dog.";

我看到的问题是向读者提供重要信息

const std::string MyClassWithALongName::kParameterOne = "The quick brown fox";
const std::string MyClassWithALongName::kParameterTwo = " jumps over";
const std::string MyClassWithALongName::kParameterThree = " the lazy dog.";

被所有模板语法所吞噬。当名称更短时,将所有内容放在一行上有助于在视觉上对样板模板语法进行分组,并允许读者自动将其过滤掉。但是,使用较长的名称是不可行的。

在这种情况下,是否存在更可读的定义这些常量的方式,从而使重要信息更加清晰?

奖金:对于这些静态const值,是否有某种魔术方法可以完全摆脱模板?显然,它们实际上根本不依赖模板类型。

3 个答案:

答案 0 :(得分:3)

如果可以使用C ++ 17,则可以使用std::string_view并将其设置为constexpr。这样,您就可以在类内部定义变量,而无需在类外部提供定义(摆脱了所有模板模板)。这样会使代码看起来像

#include <iostream>
#include <string_view>

template <typename InputT, typename OutputT>
class MyClassWithALongName {
    public:
        static constexpr std::string_view kParameterOne = "The quick brown fox";
        static constexpr std::string_view kParameterTwo = " jumps over";
        static constexpr std::string_view kParameterThree = " the lazy dog.";
};

int main() 
{
    std::cout << MyClassWithALongName<int, int>::kParameterOne;
}

Live example

答案 1 :(得分:2)

对于C ++ 17,可以使用内联变量:

template< typename InputT, typename OutputT >
class MyClassWithALongName
{
public:
    static inline const std::string kParameterOne   = "The quick brown fox";
    static inline const std::string kParameterTwo   = " jumps over";
    static inline const std::string kParameterThree = " the lazy dog.";
};

答案 2 :(得分:1)

在C ++ 17之前的版本中,您可以使用函数而不是成员数据来允许内联定义:

template <typename InputT, typename OutputT>
class MyClassWithALongName
{
public:
    static const std::string& kParameterOne()   { static const std::string s = "The quick brown fox"; return s; }
    static const std::string& kParameterTwo()   { static const std::string s = " jumps over";         return s; }
    static const std::string& kParameterThree() { static const std::string s = " the lazy dog.";      return s; }
};