2

学习 C++20 concept/requires 中,元编程时遇到一个问题

 2 years ago
source link: https://www.v2ex.com/t/826967
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

V2EX  ›  程序员

学习 C++20 concept/requires 中,元编程时遇到一个问题

  zeal7s · 1 天前 · 800 次点击

新手,刚开始学习 C++模板元编程

需求: 想实现这样一个简单的函数调用,对一个容器中的所有整数求和:

sum<IntList<1, 2, 3>>();

由于 C++标准中不允许函数模板来实现偏特化,所以我想用 concept/requires 来达到偏特化的需求。 我的实现如下:

#include <iostream>

template<int...N>
class IntList;

template<int...N>
concept IsIntList = IntList<N...>{};

template<typename T>
int sum() {
    return 0;
}

template<int...N>
requires IsIntList<N...>
int sum() {
    return (N + ...);
}

int main() {
    std::cout << sum<IntList<1, 2>>() << std::endl;
    return 0;
}

实际运行时并不能达到我想要的结果,实际在C++ Insights中输出如下:

#include <iostream>

template<int...N>
class IntList;

template<int...N>
concept IsIntList = IntList<N...>{};

template<typename T>
int sum() {
    return 0;
}

/* First instantiated from: insights.cpp:21 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
int sum<IntList<1, 2> >()
{
  return 0;
}
#endif


template<int...N>
requires IsIntList<N...>
int sum() {
    return (N + ...);
}

int main()
{
  std::cout.operator<<(sum<IntList<1, 2> >()).operator<<(std::endl);
  return 0;
}

可以看出模板实例化时并没有对第二个sum进行实例化,而是对第一个sum实例化。

请问各位大佬,在这种情况下,如何使用 concept/requires 来正确的实现我的需求?


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK