c++ - 为什么不采用非类型偏特化元组?

标签 c++ tuples c++17 typetraits

我正在尝试实现以下目标(使用 C++17 功能):

#include <type_traits>

template<auto value_>
using constant_t = std::integral_constant<decltype(value_), value_>;

template<typename ... > class Tuple {};

template<auto ... values_>
class Tuple<constant_t<values_> ... > {};

int main(void)
{
    Tuple<int, int, char> types;
    Tuple<1, 2, 3> values;
}

这让我在 g++-7.1.0 中出现以下错误

main.cpp: In function ‘int main()’:
main.cpp:15:18: error: type/value mismatch at argument 1 in template parameter list for ‘template<class ...> class Tuple’
     Tuple<1, 2, 3> values;
              ^
main.cpp:15:18: note:   expected a type, got ‘1’
main.cpp:15:18: error: type/value mismatch at argument 1 in template parameter list for ‘template<class ...> class Tuple’
main.cpp:15:18: note:   expected a type, got ‘2’
main.cpp:15:18: error: type/value mismatch at argument 1 in template parameter list for ‘template<class ...> class Tuple’
main.cpp:15:18: note:   expected a type, got ‘3’

谁能解释为什么偏特化没有为 Tuple<1, 2, 3> 激活? ?

最佳答案

1、2 和 3 不是类型。您的特化不会(也不能)更改主模板以接受值,因此您无法神奇地将值传递到之前需要类型的地方。

如果你想要一个接受值的模板,别名模板可以代替特化:

template<auto... values_>
using VTuple = Tuple<constant_t<values_>... >;

但它是一个单独的模板。

关于c++ - 为什么不采用非类型偏特化元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44897951/

相关文章:

C++ std::hash_map:键的作用是什么

c++ - 构造函数需要成员变量的参数

C++:通过简单的添加示例了解头文件和头文件保护

ios - 如何从元组中删除重复项

arrays - 如何将数组转换为元组?

c++ - 如何在 C++ 11 中迭代 std::tuple

c++ - std::vector::data() 重新分配安全吗?

c++ - GCC 上 map 迭代器错误的自动声明

c++ - 使用语法在派生类中公开基类别名模板和变量模板?

c++ - 了解 std::hardware_破坏性_interference_size 和 std::hardware_constructive_interference_size