c++ - 在 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
模块中定义,从而为编译器从其他翻译单元添加一个不可见的间接级别,我猜这可能会导致重要的效率损失,因为这些functor
s 意味着被调用数千次每个算法(图形计算)。
我能想到的最奇怪的解决方案是,如果我不能保证这些“对象唯一性”,那么我通过禁止获取对象的地址来禁止它的识别,假设用户甚至不知道 , 的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
变量)。
解决方案
推荐阅读
- tcp - tcp_retransmit_skb 的 kprobe。而不是 tcp_retransmit_skb @tcp_states,我想 kprobe __napi_schedule
- java - 过滤器不响应意图
- excel - 我需要使用 vba 将链接发布到 Excel 表中
- arrays - Array 2d VBA 可选元素
- java - SAP Hybris 自行关闭
- python - 如何通过python将行附加到csv文件中,用逗号分隔新行和上一行
- php - PHP FPDF/FPDI,希伯来字符被反转/镜像。可以修复吗?
- mysql - MySQL视图中的分组扫描所有分区
- c# - 为什么派生类不能用从原始类型派生的类型覆盖其基类中的属性?
- kubernetes - 仅当状态不是 200 时才记录 openshift livenessProbe