gpt4 book ai didi

c++ - 使用 type_traits 来限制模板成员函数的类型

转载 作者:行者123 更新时间:2023-11-28 05:44:43 25 4
gpt4 key购买 nike

我正在编写一个模板类,其中包含一个执行某些按位运算的方法,因此我想限制类型,以防在 is_integral 中使用此方法。我举了一个简单的例子 here并修改如下:

#include <iostream>
#include <type_traits>

template <typename T>
class A
{
public:
A();

T foo(T i) {
static_assert(std::is_integral<T>::value, "Integer required.");
return (i & 2);
}

private:
T x;
};

int main() {
A<double> a;
std::cout << a.foo(3) << std::endl;

return 0;
}

但是,编译器在 static_assert() 处给我 2 个编译错误:

static_assert failed "Integer required."

并在return (i & 2);:

invalid operands to binary expression ('double' and 'double')

我的问题是,如果它会在 return (i & 2); 行显示错误,无论如何,在这里使用 type_traits 检查类型似乎没有用?而且,有没有办法在运行时将错误抛出到控制台输出,而不是使其无法编译?

最佳答案

My question is, if it will show the error at line return (i & 2); anyway, using type_traits to check for type here seems useless?

的确,不幸的是你无论如何都会得到后续的编译错误,但你觉得哪个编译错误更具可读性?

  • “需要整数。”
  • 二进制表达式的无效操作数(doubledouble)

我知道我做错了第一个 - 我有 A<double>但是foo()需要一个整数。不知道第二个。我是在滥用你的类模板还是它有错误?

And, is there anyway to throw the error to console output when it runs, instead of making it unable to be compiled?

希望它是一个编译错误。在编译时捕获错误比在编译时捕获错误要好得多。

关于c++ - 使用 type_traits 来限制模板成员函数的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36461270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com