我有一个确定模板类型是否为指针的函数。

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();
}

显然,当Tstring时,无法编译此代码。有一种方法可以在val = NULL为指针类型时编译T,而在val = T()不是指针类型时编译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); }
    
  • 10-04 22:24
    查看更多