gpt4 book ai didi

c++ - 给 nullptr 一个类型来进行模板推导

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:10:13 24 4
gpt4 key购买 nike

假设以下片段:

template <class T>
void fct(T* a, T* b){
// do something
}

A a;
fct(&a, nullptr); // Problem here!

这很麻烦,因为调用参数的类型是 A*nullptr_t所以编译器无法推断模板参数 T .

一般来说,我可以想出几种解决方法:

  • 定义A* b = nullptr并使用 fct(&a, b)
  • fct 定义一个带有一个参数的重载对于 nullptr案例
  • 使用fct(&a, static_cast<A*>(nullptr))

或者是否有更简洁的解决方案,例如创建“typed nullptr”之类的东西?

最佳答案

只需将第二个参数设为非推导上下文,例如:

template <class T>
void fct(T* a, std::remove_reference<T*>::type b) {

关于c++ - 给 nullptr 一个类型来进行模板推导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32883677/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com