在特征模板中声明静态自动函数指针
Declaring static auto function pointers in traits template
我有几个针对不同数据类型的函数,我想在模板中使用,具体取决于模板参数的数据类型。我声明了一个帮助程序模板结构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的解决方案。
您可以使用:
static auto constexpr func = f;
和
static auto constexpr func = g;
当我尝试在没有 constexpr
的情况下编译时,我在 g++ 中遇到了以下错误。
g++ -std=c++11 -Wall socc.cc -o socc
socc.cc:17:24: error: ‘constexpr’ needed for in-class initialization of static data member ‘double (* traits<double>::func)()’ of non-integral type [-fpermissive]
static auto func = g;
如果没有对constexpr
的支持,一种解决方法是:
template<>
struct traits<int> {
static double func()
{
return f();
}
};
template<>
struct traits<double> {
static double func()
{
return g();
}
};
如果你不能使用 auto,你可能仍然可以使用 decltype 和类型别名:
template<> struct traits<int> {
using F = decltype(&f);
const static F func;
};
const traits<int>::F traits<int>::func= f;
这比显式方法更好还是更差,由您决定。
当然,您也可以省略类型别名,如果您不需要它:
template<> struct traits<int> {
const static decltype(&f) func;
};
const decltype(&f) traits<int>::func = f;
相关文章:
- QMetaObject invokeMethod的基于函数指针的语法
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- c++r值引用应用于函数指针
- 模板函数指针和lambda
- 是否可以将llvm::FunctionType转换为C/C++原始函数指针
- 带有类的函数指针
- () 函子后面的括号,而不是函数指针?
- 全局作用域中函数指针的赋值
- 使用"Task"函数指针队列定义作业管理器
- 将成员函数指针作为参数传递给模板方法
- 如何创建对象函数指针C++映射?
- 匹配函数指针作为模板参数?
- 通过函数指针定义类范围之外的方法
- 存储在类中的函数指针
- C++从函数指针数组调用函数
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 整数键映射到头文件中的成员函数指针
- 从类成员函数到类 C 函数指针的转换
- 如何将内联匿名函数分配给C++函数指针
- 将字符缓冲区强制转换为函数指针