c++ - 将 nullptr 传递给可变模板指针

标签 c++ c++11 variadic-templates

我目前有以下功能:

template <typename T, typename... Args> void Get(T* out, Args*... other);
template <typename T> void Get(T* out);
template <> void Get<int>(int* out);
template <> void Get<int64>(int64* out);
template <> void Get<double>(double* out);
template <> void Get<char*>(char** out);
template <> void Get<void*>(void** out);

调用使用:

Get(&i, &t, &f);

iinttchar*f作为double

如果我想传递一个空指针,这非常有用,但有一个异常(exception)。

Get(&i, nullptr, nullptr, &t, &f);

给予

main.cpp: In function ‘int main()’:
main.cpp:94:39: error: no matching function for call to ‘Get(int*, std::nullptr_t, std::nullptr_t, char**, float*)’
  Get(&i, nullptr, nullptr, &txt, &f);
                                       ^
main.cpp:94:39: note: candidates are:
main.cpp:18:46: note: template<class T, class ... Args> void Get(T*, Args* ...)
 template <typename T, typename... Args> void Get(T* out, Args*... other)
                                              ^
main.cpp:18:46: note:   template argument deduction/substitution failed:
main.cpp:94:39: note:   mismatched types ‘Args*’ and ‘std::nullptr_t’
  Get(&i, nullptr, nullptr, &txt, &f);
                                       ^
main.cpp:28:28: note: template<class T> void Get(T*)
 template <typename T> void Get(T* out)
                            ^
main.cpp:28:28: note:   template argument deduction/substitution failed:
main.cpp:94:39: note:   candidate expects 1 argument, 5 provided
  Get(&i, nullptr, nullptr, &txt, &f);
                                       ^

我如何重写我的 Get 函数以保持旧用法,除了它们也将接受 nullptr

最佳答案

你可以这样做:

template <typename T, typename... Args>
typename std::enable_if<std::is_same<std::nullptr_t, T>::value || std::is_pointer<T>::value>::type
Get(T out, Args... other);

template <typename T>
typename std::enable_if<std::is_same<std::nullptr_t, T>::value || std::is_pointer<T>::value>::type
Get(T out);

所以你的专长是不同的:

template <> void Get<int*>(int* out);
template <> void Get<int64*>(int64* out);
template <> void Get<double*>(double* out);
template <> void Get<char**>(char** out);
template <> void Get<void**>(void** out);

并且可能:

template <> void Get<nullptr_t>(nullptr_t); // the new one

顺便说一句,您可能更喜欢重载(对于带有一个参数的 Get):Live example .

关于c++ - 将 nullptr 传递给可变模板指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25386695/

相关文章:

c++ - 在 DirectShow 中保持纵横比? (窗口)C++

c++ - 函数模板作为成员 - GCC 与 CLANG

c++ - 为什么复制构造函数与移动构造函数一起被调用?

c++ - 在编译时生成一个零序列

c++ - 如何定义函数模板中使用的函数?

c++ - 这是未定义的行为还是误报警告?

c++ - 为什么使用单个赋值运算符处理复制和 move 赋值效率不高?

c++ - 如果作为参数传递的仿函数不带参数,则启用模板

c++ - 启用 C++11 时如何修复 'wrong number of template arguments''?

c++ - 已经 "EOF"ed ifstream 上的 peek() 是否继续返回 EOF?