c++ - 模板 enable_if 函数实现是否可行?
问题描述
使用 c++14,我有一些类似于以下的函数声明。
template <class... Args>
struct potato {
template <class T, class = std::enable_if_t<!std::is_same<T, int>::value>>
const T& blee(size_t blou) const;
template <class T, class = std::enable_if_t<std::is_same<T, int>::value>>
const T& blee(size_t blou) const;
};
是否可以单独实现这些功能?据我所知,编译器无法弄清楚是什么实现了什么。例如 :
template <class... Args>
template <class T, class>
const T& potato<Args...>::blee(size_t blou) const {
// do something
}
template <class... Args>
template <class T, class>
const T& potato<Args...>::blee(size_t blou) const {
// do something
}
那时信息就丢失了enable_if
。我是否在我的工具包中遗漏了一个技巧来完成这项工作?请注意,我宁愿不使用返回类型enable_if
或参数enable_if
,因为它们是不虔诚的。
编辑:更新以更好地代表我的用例。
解决方案
你真的不需要enable_if
那个:
template<class T>
const T& blee(size_t blou) const {
// do something
}
template<>
const int& blee<int>(size_t blou) const {
// do something
}
编辑:由于您的函数位于类模板中,因此您必须使用标签调度:
template<class... Args>
struct potato {
template<class T>
void blee() const;
private:
void realBlee(std::true_type) const;
void realBlee(std::false_type) const;
};
template<class... Args>
template<class T>
void potato<Args...>::blee() const {
realBlee(std::is_same<T, int>());
}
template<class... Args>
void potato<Args...>::realBlee(std::true_type) const {
std::cout << "int\n";
}
template<class... Args>
void potato<Args...>::realBlee(std::false_type) const {
std::cout << "generic\n";
}
或类似的东西,例如 constexpr 如果:
template<class... Args>
struct potato {
template<class T>
void blee() const;
private:
void intBlee() const;
};
template<class... Args>
template<class T>
void potato<Args...>::blee() const {
if constexpr (std::is_same_v<T, int>) {
intBlee();
} else {
std::cout << "generic\n";
}
}
template<class... Args>
void potato<Args...>::intBlee() const {
std::cout << "int\n";
}
推荐阅读
- python - 如何停止在执行程序中运行的循环?
- spring - 在 GCP 中无法访问 Spring Boot REST API
- python - 池映射没有性能提升
- java - Java:当应用程序使用 Procrun 注册为 Windows 服务时,使用 ProcessBuilder 运行批处理文件
- javascript - 如何使 clearTimeout 正常工作以取消(中断)setTimeout 循环?
- asp.net - 在具有 3 个外键的数据库中插入记录
- django - urlpatterns 的行为不符合预期
- konvajs - 有什么方法可以设置/获取 konva 形状的数据?
- python - 关于 Keras/Tensorflow 中超参数调优的问题
- c# - CRUD 的泛型类 - C# 中使用存储库和工作单元模式的依赖注入