通过在编译时使用traits通过模板类抛出错误来禁用函数 [英] Disable a function by throwing error at compile-time with template class using traits

查看:180
本文介绍了通过在编译时使用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
}

这篇关于通过在编译时使用traits通过模板类抛出错误来禁用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆