我正在开发一个元编程项目,我们希望能够将浮点数作为模板参数传递。我不确定这个问题是否会更适合堆栈交换,但我认为这是一个有点概念,所以选择了这个网站。如何将浮点数作为模板参数传递?
基本上,我想这样做:
template <double var>
double fun() { return var; }
int main()
{
double myDoble = fun<1.0>();
return 0;
}
显然,这无法做到的。此链接(http://en.cppreference.com/w/cpp/language/template_parameters)清楚地表明,作为模板参数传递的类型必须是下列之一:
integral type
enumeration
pointer to object or to function
lvalue reference to object or to function
pointer to member object or to member function
std::nullptr_t (since C++11)
然而,事实证明,我可以一个指针的指针传递给一个对象(也许是一个struct包含一个double?)让我怀疑,通过传递一个指向这样的double的方法可能有一种实现上述的方法。
所以,我想这一点:
template <double* pVar>
double fun()
{
return *pVar;
}
int main() {
static const double param = 1.2;
double value = fun<¶m>();
return 0;
}
它提供了以下错误:
prog.cpp:9:29: error: ‘& param’ is not a valid template argument of type ‘double*’ because ‘param’ has no linkage
double value = fun<¶m>();
我认为这个问题可能是因为我使用的是原始的,所以我尝试这样做:
struct D
{
double val;
};
template <D* pD>
double fun()
{
return pD->val;
}
int main() {
static const D d{1.2};
double value = fun<&d>();
return 0;
}
它给出了相同的错误。
有没有人有解决这个问题的其他想法?如果人们能够避免“不能做到”的答案,我将不胜感激;我知道这是无法完成的,无论如何我都想做! ;)
使它成为一个全球性的。 PS:你可以使用引用而不是指针。 –
@ThomasEding我无法让它工作; http://ideone.com/LGDv1j – arman
你为什么需要它?为什么它必须在编译时完成(即使用模板)?也许这是一个[XY问题](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) –