在这种情况下,如何正确使用 std::enable_if

how to use std::enable_if correctly in this case

本文关键字:std enable if 这种情况下 何正确      更新时间:2023-10-16

我定义了以下方法:

template <typename Interface>
Interface Create();

通过此实现:

template <typename Interface>
typename std::enable_if<std::is_pointer<Interface>::value, Interface>::type Create()
{
...
}

但现在我收到以下错误:"对 ITestInterface* Create()的未定义引用"

当我删除std::enable_if时,一切正常。但是我需要它工作,因为我想添加此功能的版本,当接口是参考或接口是std::vector时可以工作。我在这里做错了什么?我还注意到这是一个链接器错误 - 但我不知道为什么。有人可以给我一个提示吗?

而在正常函数中,返回类型不是签名的一部分,返回类型确实是模板函数签名的一部分。
所以

template <typename Interface> Interface Create();

不同于

template <typename Interface>
typename std::enable_if<std::is_pointer<Interface>::value, Interface>::type
Create();

您必须在声明和定义中使用相同的签名。

由于函数无法进行部分专用化,因此必须使用帮助程序类:类似的东西可能会有所帮助:

namespace detail
{
template <typename > struct CreateHelper;
template <typename T> struct CreateHelper<T*>
{
    static T* create() {
        // Implementation with T*
    }
};
template <typename T> struct CreateHelper<T&>
{
    static T& create() {
        // Implementation with T&
    }
};
template <typename T> struct CreateHelper<std::vector<T>>
{
    static std::vector<T> create() {
        // Implementation with std::vector<T>
    }
};
} // namespace detail

template <typename Interface> Interface Create()
{
    return detail::CreateHelper<Interface>::create();
}