如何使用enable_if对模板类成员进行离线定义

问题描述 投票:0回答:1

我试图了解enable_if的用法,但在同一方面确实没有什么困难。在这里,我编写了一个似乎无法按预期工作的测试代码。

#include <iostream>

template <typename T>
class Base{
 public:
  template <typename U>
  U Compute(U a, U b);
};

using AddOperation = Base<int>;

template<>
template<typename U>
typename std::enable_if<!std::is_same<U, bool>::value, U>::type
AddOperation::Compute(U a, U b){
  return a + b;
}

int main(){
  Base<int> b;
  std::cout << b.Compute<int>(10, 2) << std::endl;
  std::cout << b.Compute<bool>(true, false) << std::endl;
  return 0;
}

意图:不想为bool类型启用计算

但是在上面的代码中,它正在工作。如何确保bool的Compute函数未由编译器专用?

c++ class templates template-specialization
1个回答
0
投票

您也应该像定义一样在声明中使用enable_if

© www.soinside.com 2019 - 2024. All rights reserved.