【问题标题】:why c++ cannot infer templated nontype template argument?为什么 c++ 不能推断模板化的非类型模板参数?
【发布时间】:2018-01-15 20:29:42
【问题描述】:

代码如下:

template <typename T, int P> struct _t_test_struct{
    T t;
    int p=P;
};
typedef _t_test_struct<float, 6> _test_struct6;

template <typename T, typename TP, TP P, template<typename, TP> class C>
void test1(C<T,P> &x){
    std::vector<T> _a;
    _a.resize(P);
    _a[0] = x.t;
    std::cout<<"typeid(P):"<<typeid(P).name()<<std::endl;

};

_test_struct6 _testp;
    _testp.t = 10;
    test1(_testp);

为什么编译器无法确定TPint?我只能称它为test1&lt;float, int&gt;(_testp)

【问题讨论】:

  • 在这里工作coliru.stacked-crooked.com/a/40999945ca7f280f。你遇到了什么错误?
  • @0x499602D2 - 因为您编译 C++17 而有效。但是 OP 将这个问题标记为 C++11。我想,如果你编译 C++11 或 C++14,你会得到一个编译错误。

标签: c++ c++11 templates template-argument-deduction


【解决方案1】:

为什么编译器无法确定TPint?我只能称它为test1&lt;float, int&gt;(_testp)

如果您编译 C++11 或 C++14,则不能。

如果你编译C++17可以,因为C++17改进了模板推导规则。

建议:看看corresponding page in CPP Reference

如果我理解正确的话,问题是直到 C++17 “模板类型参数不能从非类型模板参数的类型推导出来”。

在你的情况下,

template <typename T, typename TP, TP P, template<typename, TP> class C>
void test1(C<T,P> &x)

TP 类型不能从 P 推导出来,TP 值(但如果你显式 TP 调用 test1&lt;float, int&gt;(_testp) 则有效)

从 C++17 开始,“当从表达式推导出与声明为依赖类型的非类型模板形参 P 对应的实参值时,P 类型中的模板形参推导自值的类型。”,所以TPP推导出来。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 2015-02-06
    • 1970-01-01
    • 2011-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多