jdm*_*jdm 5 c++ templates constexpr
我有一个模板函数,有一点我想根据模板参数使用不同的代码:
template <typename T>
void function(const T ¶m) {
// generic code here...
// pseudo-code:
if constexpr isinstance(param, Banana) {
param.peel();
} else if constexpr isinstance(param, Apple) {
// do nothing, Apple has no method `peel`
}
}
Run Code Online (Sandbox Code Playgroud)
我不想专门研究整个功能,因为大多数代码都是共享的。我要插入的语句实际上是一种临时调试措施。我知道正确的做法是创建一个重载函数,doPeel然后调用它:
void doPeel(const Banana ¶m) { param.peel(); }
void doPeel(const Apple ¶m) {}
Run Code Online (Sandbox Code Playgroud)
但是我很好奇,有没有一种方法可以在编译时告诉函数中某个给定变量的类型(模板专门化)是什么...以便使用仅针对一种类型进行编译的语句?
我不知道这样的事情是否可以实现constexpr-还是编译器在废弃分支中强制执行类型?我还尝试使用lambda进行处理-为这两种情况都定义lambda,并且仅调用其中一种,但是我找不到解决方法。有任何想法吗?
if constexprC++17中有:
template<typename T>
void foo(T const& t)
{
if constexpr(is_same<decay_t<T>, int>::value) {
cout << __PRETTY_FUNCTION__ << " " << t * 2 << endl;
} else {
cout << __PRETTY_FUNCTION__ << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
在 C++14 中,你可以破解如下内容:
template<typename T>
void foo(T const& t)
{
conditional_eval<is_same<decay_t<T>, int>>([=](auto){
cout << __PRETTY_FUNCTION__ << " " << t * 2 << endl;
},[](auto){
cout << __PRETTY_FUNCTION__ << endl;
});
}
Run Code Online (Sandbox Code Playgroud)
定义为conditional_eval:
template<typename IfTrue, typename IfFalse>
void conditional_eval_impl(std::true_type, IfTrue&& t, IfFalse&&) {
t(0);
}
template<typename IfTrue, typename IfFalse>
void conditional_eval_impl(std::false_type, IfTrue&&, IfFalse&& f) {
f(0);
}
template<typename Tag, typename IfTrue, typename IfFalse>
void conditional_eval(IfTrue&& t, IfFalse&& f) {
conditional_eval_impl(Tag{}, std::forward<IfTrue>(t), std::forward<IfFalse>(f));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
179 次 |
| 最近记录: |