为什么 C++ 不能推断模板化的非类型模板参数?

why c++ cannot infer templated nontype template argument?

代码如下:

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<float, int>(_testp).

Why the compiler cannot determine the TP is int? I can only call it like test1<float, int>(_testp).

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

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

建议:看看corresponding page in CPP Reference.

如果我理解正确的话,问题是直到 C++17 "Template type argument cannot be deduced from the type of a non-type template argument".

在你的情况下,

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

无法从 P 中推导出 TP 类型,一个 TP 值(但如果显式 TP 调用 test1<float, int>(_testp) 则有效)

从C++17开始,"When the value of the argument corresponding to a non-type template parameter P that is declared with a dependent type is deduced from an expression, the template parameters in the type of P are deduced from the type of the value.",所以TPP推导。