我有一个判断模板类型是否为指针的函数。
template<class T>
struct is_pointer_struct { static const bool value = false; };
template<class T>
struct is_pointer_struct<T*> { static const bool value = true; };
template<class T>
bool is_pointer(T &var) {
return is_pointer_struct<T>::value;
}
我有一个初始化函数。
template<class T>
void initialize(T &val) {
if (is_pointer(val))
val = NULL;
else
val = T();
}
很明显,当T
为string
时,这段代码无法编译。有没有办法在 T
是指针类型时编译 val = NULL
并在 T
时编译 val = T()
> 不是指针类型?
最佳答案
在您的特定情况下,您可以使用统一初始化,如 VTT说:
val = T{};
此外,标准库还提供 std::is_pointer
.
作为对更一般性问题的回答
在 C++17 中,您只需将
if(...)
更改为if constexpr(...)
:template<class T> void initialize(T &val) { if constexpr(is_pointer(val)) val = nullptr; else val = T(); }
在 C++14 中,你 can implement your own
static_if
.在 C++03/11 中,您可以使用标签调度:
template <typename T> void initialize_impl(std::true_type /* pointer */, T& val) { val = NULL; } template <typename T> void initialize_impl(std::false_type /* non-pointer */, T& val) { val = T(); } template<class T> void initialize(T &val) { initialize_impl(std::is_pointer<T>{}, val); }
关于c++ - 我可以在 C++ 中部分编译模板函数吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45008597/