在这种情况下,如何正确使用 std::enable_if
how to use std::enable_if correctly in this case
我定义了以下方法:
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();
}
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从持续时间构造std::chrono::system_clock::time_point
- std::具有相同基类的类的变体
- std::向量与传递值的动态数组
- 使用std::vector的OpenCL矩阵乘法
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- std::condition_variable::wait()如何评估给定的谓词
- 如何获取std::result_of函数的返回类型
- std::原子加载和存储都需要吗
- 将对象移动到std::shared_ptr
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 使用一个考虑到std::map中键值的滚动或换行的键
- 如何从 std::atomic 中提取指针 T<T>?
- 为什么 std::unique 不调用 std::sort?
- 使用std::函数映射对象方法
- Linux gnu++11,在运行时获取"Enable multithreading to use std::thread: Operation not permitted"