【问题标题】:Less verbose templated private static const member variable specialisation不那么冗长的模板化私有静态 const 成员变量特化
【发布时间】:2016-03-12 05:43:25
【问题描述】:

所以如果我想专攻:

template<typename T>
class my_class{
       private:
          static const std::string my_string;
        };

我能做到的唯一方法是通过

template<> const std::string my_class<some_type>::my_string = "the string";

假设我有一堆私有静态成员和一堆专业。

有没有更清洁的方法来做到这一点?更接近:

my_class<some_type>::my_string = "the string";

【问题讨论】:

  • 变量模板,也许?
  • 这可能是一个很好的拍摄,但我不知道如何使用它们。

标签: c++ constants static-members template-specialization c++17


【解决方案1】:

一种方法是标签调度。

template<class T> struct tag_t{using type=T;};
template<class T> constexpr tag_t<T> tag={};

auto make_my_string(tag_t<some_type>){return "the string";}

然后:

template<typename T>
class my_class{
private:
  static const std::string my_string;
};

template<class T>
static const std::string my_class<T>::my_string = make_my_string( tag<T> );

每种类型的开销是:

auto make_my_string(tag_t<some_type>){return "the string";}

这比替代方案更干净。作为一个优势,您可以在与some_type 相邻的命名空间中定义make_my_stringmy_class 应该会通过 ADL 自动获取它。

由于您有一堆私有静态 const 成员,您也可以将它们全部放入自己的结构中。然后,您可以让一个函数为给定类型创建所有这些,而不是每个私有静态 const 成员一个函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-02
    • 2017-01-16
    • 1970-01-01
    • 1970-01-01
    • 2011-03-19
    • 1970-01-01
    相关资源
    最近更新 更多