通过在编译时使用traits通过模板类抛出错误来禁用函数

通过在编译时使用traits通过模板类抛出错误来禁用函数

问题描述:

我有一个类,让我们把它叫做 Foo 有几个方法:

I have a class, let's call it Foo with several methods:

template<typename T>
class Foo {
public:
   Foo()               { /* ... */ }
   bool do_something() { /* ... */ }

   // This method should be callable only if:
   // std::is_floating_point<T>::value == true
   void bar() { 
      // Do stuff that is impossible with integer
   }
};



我想要能够构造 Foo< double> Foo 但是我不想允许调用 bar()类型T不是浮点类型。我也希望错误在编译时生成,而不是在运行时。所以,我想要的是:

I would like to be able to construct both Foo<double> and Foo<int> But I don't want to allow calls to bar() when the type T is not a floating point type. I also want the error to be generated at compile-time and not at the run-time. So, what I want is:

Foo<double> a;
a.bar();                        // OK
Foo<int> b;
bool res = b.do_something();    // OK
b.bar();                        // WRONG: compile error



我尝试了很多事情与 enable_if (包含这一个),但我不能再使用 int 键入 Foo 。例如:

I tried a lot of things with enable_if (with posts like this or this one) but I can't use anymore the int type with Foo. For example:

typename std::enable_if<std::is_floating_point<T>::value>::type
bar() { /* ... */ } 

main.cpp:112:28:   required from here
foo.h:336:5: error: no type named ‘type’ in ‘struct std::enable_if<false, void>’
 bar() {

如何限制对浮点类型使用 bar(),但允许整数类型在其他地方使用?

How can I constrain the use of bar() to floating point types but allow integer type to use in other places?

void bar() { 
   static_assert(std::is_floating_point<T>::value,
                 "this method can only be called for floating-point Foos!");
   // do stuff
}