除非T :: answer是整数类型,否则如何强制模板替换失败?

时间:2015-05-19 12:58:00

标签: c++ sfinae enable-if

我有以下代码:

#include <type_traits>

struct SA {};
struct SB { static const int answer = 42; };
const int SB::answer;

template <typename T>
int F() {
  return T::answer;
}

int main(int argc, char **argv) {
  (void)argc; (void)argv;
  // F<SA>();  // I want to make this a template substitution failure.
  return F<SB>();  // This should still work.
}

我想让调用F<SA>()成为模板替换失败。我尝试将int F更改为typename std::enable_if<std::is_integral<T::answer>::value, int>::type F,但我收到以下错误:

$ g++ --versiong++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2
$ g++ -W -Wall -Wextra -Werror -std=c++0x -fno-diagnostics-show-caret ei.cc && ./a.out
ei.cc:8:55: error: to refer to a type member of a template parameter, use ‘typename T:: answer’ [-fpermissive]
ei.cc: In function ‘int main(int, char**)’:
ei.cc:16:20: error: no matching function for call to ‘F()’
ei.cc:16:20: note: candidate is:
ei.cc:8:76: note: template<class T> typename std::enable_if<std::is_integral<typename T::answer>::value, int>::type F()
ei.cc:8:76: note:   template argument deduction/substitution failed:
ei.cc: In substitution of ‘template<class T> typename std::enable_if<std::is_integral<typename T::answer>::value, int>::type F() [with T = SB]’:
ei.cc:16:20:   required from here
ei.cc:8:76: error: no type named ‘answer’ in ‘struct SB’

这是试图在answer中查找名为struct SB的类型,但我想让它在answer中查找名为struct SB的整数字段。

2 个答案:

答案 0 :(得分:3)

我发现在模板参数中放入enable_if检查会使您的界面更清晰:

template <typename T,
          std::enable_if_t<std::is_integral<decltype(T::answer)>::value>* = nullptr>
int F() {
  return T::answer;
}

甚至更清楚,使用R. Martinho Fernandes&#39; Remastered enable_if

namespace detail {
    enum class enabler {};
}
template <typename Condition>
using EnableIf = std::enable_if_t<Condition::value, detail::enabler>;

template <typename T, EnableIf<std::is_integral<decltype(T::answer)>>...>
int F() {
  return T::answer;
}

答案 1 :(得分:0)

添加<IfModule>似乎有效:将decltype(...)更改为int F