c++ - C++模板短路逻辑AND(&&)

标签 c++ templates short-circuiting

有人告诉我模板中的逻辑和(&&)不起作用,所以我想使用模板专门化来实现它。

我的测试代码如下:

#include <iostream>

template <bool b1, bool b2>
constexpr static bool andVal = false;

// template specialization
template <bool b2>
constexpr static bool andVal<true, b2> = b2;

int main(int argc, char *argv[]) {
  std::cout << andVal<1, 1> << std::endl;
  std::cout << andVal<0, 1> << std::endl;
  std::cout << andVal<0, 0> << std::endl;
  std::cout << andVal<1, 0> << std::endl; // this line will cause compilation error
  return 0;
}

但是当我编译代码时,会发生如下错误:
/tmp/ccaqDdfO.s: Assembler messages:
/tmp/ccaqDdfO.s:369: Error: symbol `_ZL6andVal' is already defined

如果我在最后一行测试代码std::cout << andVal<1, 1> << std::endl;注释,则编译将成功并且测试结果正确。

模板功能有什么问题?为何已经定义?

任何答复将不胜感激!

最佳答案

模板很好。这是gcc 5.4至6.1版本的错误:template specialization compile error。您恰好位于错误版本范围的底部。

关于c++ - C++模板短路逻辑AND(&&),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59910405/

相关文章:

c++ - Debug模式下未处理的异常,但在发布时工作正常

c++ - 如何为 cocos2dx 窗口设置标题和全屏标志

c++ - dynamic_cast 中的模糊转换

python - 为什么 Python 返回 [15] for [0xfor x in (1, 2, 3)]?

java - Iterable 上的短路逻辑运算符

c++ - 如何将 Windows 服务连接到控制台 session

c++ - 我如何找出数组中的哪个元素具有最高值?

C++ 为特定模板特化添加重载方法

c++ - 模板模板参数或模板参数

php - 如何在 Twig 中检查 null?