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

Max*_*ant 3 c++ traits c++11 template-classes

我有一个类,让我们Foo用几种方法调用它:

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
   }
};
Run Code Online (Sandbox Code Playgroud)

我希望能够构建既Foo<double>Foo<int>,但我不希望允许调用bar()当类型T不是一个浮点类型.我还希望在编译时生成错误,而不是在运行时生成错误.所以,我想要的是:

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

我尝试了很多事情enable_if(与像帖子这个这一个),但我不能再使用的int类型Foo.例如:

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() {
Run Code Online (Sandbox Code Playgroud)

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

Bri*_*ian 12

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

  • @MaximeLorant唯一的问题是`bar`参与重载决策.如果有另一个"bar"覆盖,那么这个可能仍然是首选,然后意外调用.请注意,天真的SFINAE解决方案也无法正常工作. (2认同)