【问题标题】:Achieving an SFINAE-like effect in an if-else block在 if-else 块中实现类似 SFINAE 的效果
【发布时间】:2016-05-12 00:48:44
【问题描述】:

我希望能够写出类似的东西

template <typename T> void foo() {
    // ...
    if (is_nice<T>::value) {
        bar_which_is_defined_only_for_nice_types<T>();
    }
}

但是,当我尝试编译它时(g++ 4.9.3,没有优化),我收到了关于 bar_which_is_defined_only_for_nice_types 的投诉。如何在不诉诸 foo() 的 2 个定义的情况下达到预期的效果?

【问题讨论】:

  • 这种方式是不可能的。是对open std的提议。在下面@Praetorian 的asnwer 中使用函数重载。

标签: c++ templates c++11 conditional-compilation


【解决方案1】:

您可以根据is_nice&lt;T&gt;标记调度

#include <type_traits>

template<typename T>
struct is_nice : std::false_type {};
template<>
struct is_nice<int> : std::true_type {};

template<typename T>
void do_nice_things(std::true_type)
{
    bar_which_is_defined_only_for_nice_types<T>();
}

template<typename T>
void do_nice_things(std::false_type)
{
}

template <typename T>
void foo()
{
    do_nice_things<T>(is_nice<T>{});
}

【讨论】:

    猜你喜欢
    • 2010-12-06
    • 1970-01-01
    • 1970-01-01
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    • 2011-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多