有人告诉我模板中的逻辑和(&&
)不起作用,所以我想使用模板专门化来实现它。
我的测试代码如下:
#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/