防止模板参数上的ADL
Prevent ADL on template parameters
我目前有一个类模板,它采用了一系列类型。每个类型可能都需要用类本身进行实例化。我目前拥有的是这样的东西:
template <typename... Types>
struct TypeList; // Not defined
struct Placeholder; // Not defined
template <typename Types, typename AnotherType = Default>
class MyClass
{
// ...
};
然后你可以这样使用它:
typedef MyClass<TypeList<Container1<Placeholder>, Container2<std::string,
Placeholder>, OtherType>, OptionalType> MyTypedef;
MyTypedef my_object;
MyClass
将用它自己替换Placeholder
的外观,使用生成的类型,一切都很好。
当我尝试做以下任何一种事情时,问题就会出现:
MyTypedef *my_ptr = &my_object;
my_free_function(my_object);
这两种情况都会导致编译器错误,因为编译器试图实例化Container1<Placeholder>
和Container2<std::string, Placeholder>
以执行参数相关查找(ADL),而Placeholder
本身的实例化失败。
我知道可以通过做例如来避免ADL
MyTypedef *my_ptr = std::addressof(my_object);
(my_free_function)(my_object);
然而,我不想让MyClass
的用户不断抑制ADL。有没有其他直接的方法让用户提供一个类型列表,而不将这些类型用于ADL?
好吧,一切都好了。诀窍是使用依赖类型,而不是直接使用模板。我的最终解决方案是将TypeList定义如下:
template <typename... Types>
struct TypeList
{
private:
struct Holder
{
private:
typedef TypeList<Types...> InnerTypeList;
template <typename Types, typename AnotherType>
friend class MyClass;
};
public:
typedef Holder type;
};
然后,MyClass的用户可以进行
typedef MyClass<TypeList<Container1<Placeholder>, Container2<std::string,
Placeholder>::type, OtherType>, OptionalType> MyTypedef;
MyTypedef my_object;
注意添加了"::type"
最后,在MyClass中,我替换了
typedef typename SubstituteType<Types, Placeholder, MyClass>::type InternalTypeList;
带有
typedef typename SubstituteType<Types::InnerTypeList, Placeholder, MyClass>::type
InternalTypeList;
给了我与以前相同的CCD_ 7类型。
因为依赖类型Holder
没有自己的模板参数,所以编译器不必为了ADL的目的实例化占位符类型,并且一切都正常工作。
相关文章:
- 如何反转整数参数包
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 函数调用中参数的顺序重要吗
- 部分定义/别名模板模板参数
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 使用不带参数的函数访问结构元素
- ADL 和非类型模板参数
- 带有 std::function 的 ADL:可以通过 std::function 参数列表中的类型找到采用 std::function 对象的函数吗?
- ADL 失败(或未完成?)具有附加(非推导)模板参数的函数
- 对于类型是类模板专业化的参数,ADL背后的理由是什么
- 考虑模板参数的参数相关外观 (ADL)?
- 通常的不合格查找和与参数有关的名称查找(ADL)
- 当存在lambda参数时,ADL将失败
- ADL 不考虑与模板参数关联的命名空间吗?
- 防止模板参数上的ADL