首页 > 解决方案 > 在 C++0x 中定义“内联”变量

问题描述

我正在从没有对 C++11 的不完全但高度支持的环境中开发一组函数,这些函数旨在既可以通过一组参数调用,又可以轻松传递给更高级别的函数,而无需强制用户通过强制转换等方式强制模板参数实例化。因此,创建这些函数最明显的解决方案是通过以下方式创建仿函数:

namespace mylib {

   struct functor_f
   {
      return_type_1 operator()(type1, type2) const
      { return something; }

      template<class Type3>
      return_type_2 operator()(type1, type2, Type3) const
      { return something2; }
   };

   static auto functor = functor_f();
}

这种方法的问题在于,functor每个翻译单元会有不同的地址,这可能会导致问题,具体取决于用户如何处理functor. 如果我删除static,那么我必须functor在一个.cpp模块中定义,从而为编译器从其他翻译单元添加一个不可见的间接级别,我猜这可能会导致重要的效率损失,因为这些functors 意味着被调用数千次每个算法(图形计算)。

我能想到的最奇怪的解决方案是,如果我不能保证这些“对象唯一性”,那么我通过禁止获取对象的地址来禁止它的识别,假设用户甚至不知道 , 的std::address_of存在喜欢:

namespace mylib {
   namespace _impl {
      template<class...>
      constexpr bool always_false() { return false; }
   }

   template<class T = void>
   struct non_addressable
   {
      // Or just make-it private, but I would prefer a cleaner
      // compile-time diagnostic.
      void operator&() const
      { static_assert(_impl::always_false<T>(), "Don't address me"); }
   };

   struct functor_f : non_addressable<>
   {
      return_type_1 operator()(type1, type2) const
      { return something; }

      template<class Type3>
      return_type_2 operator()(type1, type2, Type3) const
      { return something2; }
   };

   static auto functor = functor_f();
}

但我一点也不喜欢它,而且我不完全确定这种设计的副作用。

有任何 C++14 之前的习语可以实现这样的目标吗?(模拟inline变量)。

标签: c++c++11functorlinkage

解决方案


推荐阅读