模板typename为同一模板的其他参数的类型

Template typename as type of other parameter of the same template

本文关键字:其他 参数 类型 typename 模板      更新时间:2023-10-16

我想创建一个模板,在那里我可以使用不同的矢量类型,和一个常量作为相同类型的矢量。我希望能够传递常量作为模板参数,以便让编译器优化它,而不需要显式特化。

所以我尝试重新使用类型参数,但我得到了非法的类型。

#include <vector>
using namespace std;
template<typename WEIGHT, WEIGHT multiplier>
void test_multipier(vector<WEIGHT> &v)
{
    uint16_t num = 16;
    /*...*/
    WEIGHT w = multiplier* (num);
    v.push_back(w);
}
int main()
{
    vector<double> test_vector;
    test_multipier<double,0.01>(test_vector); 
    //^^ Error C2993 'double': illegal type for non-type template parameter 'multiplier'

    return 0;
}

摘自cppreference.com:

[非类型模板形参的类型]是以下类型之一(可选的cv限定,限定符将被忽略):

  • std::nullptr_t (c++ 11起);
  • 积分类型;
  • 左值引用类型(对象或函数);
  • 指针类型(指向对象或函数);
  • 指向成员类型(指向成员对象或成员函数)的指针;
  • 枚举类型。

double不能用作非类型模板参数