【问题标题】:Why is the non-type partial specialization tuple not taken?为什么不采用非类型偏特化元组?
【发布时间】:2017-07-04 05:58:33
【问题描述】:

我正在尝试实现以下目标(使用 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&lt;1, 2, 3&gt; 的部分特化没有激活?

【问题讨论】:

    标签: c++ tuples c++17 typetraits


    【解决方案1】:

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

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

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

    但它是一个单独的模板。

    【讨论】:

    • 这就是我一直试图避免的(别名)
    • 但是谢谢你,你有解释为什么不能改变主模板来接受值吗?
    • @FletcherBlight - 专业化的本质。值不是类型的更特殊形式。它只是一个类型。它具有类型的事实不允许将其替换为类型。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-19
    • 1970-01-01
    • 2019-10-01
    • 1970-01-01
    • 2020-12-08
    • 1970-01-01
    相关资源
    最近更新 更多