对于我想在模板中使用的不同数据类型,我有几个函数,这取决于模板参数的数据类型。我宣布了一个辅助模板struct traits
,并将其专用于相应的数据类型。在特征模板中声明静态自动函数指针
我的问题是:是否有可能避免在这些专业化中编写确切的函数签名?另外,是否可以避免在模板声明之外定义这些函数,并且仍然有这些函数static
?
下面是我想要做的非常简单的例子。我会如使用的语法已被注释掉,但它显然不能编译。
#include <iostream>
int f() { return 1; }
double g() { return 2.3; }
template<typename T>
struct traits;
template<>
struct traits<int> {
// static auto func = f;
int(*func)() = f;
};
template<>
struct traits<double> {
// static auto func = g;
double(*func)() = g;
};
template<typename T>
struct traits_user {
void output() {
// std::cout << traits<T>::func() << " ";
std::cout << traits<T>().func() << " ";
}
};
int main()
{
traits_user<int>().output();
traits_user<double>().output();
}
编辑 虽然通过@RSahu答案实际上是完美的,我不能,因为我坚持用VS2013一段时间更多的使用它。适合VS2013的解决方案将非常受欢迎。
谢谢!不幸的是,我现在坚持使用VS2013,它不支持constexpr。任何其他想法?我编辑了答案并为你+1了。 – Rostislav
所以我想没有办法重复功能签名(他们当然在我的真实代码中更加精细)。它是否正确? – Rostislav
@Rostislav,由于VS2013不支持所有的C++ 11功能,我觉得很难建议一个不同的工作。这对我没有快速访问VS2013没有帮助。 –