在特征模板中声明静态自动函数指针

Declaring static auto function pointers in traits template

本文关键字:函数 指针 静态 声明 特征      更新时间:2023-10-16

我有几个针对不同数据类型的函数,我想在模板中使用,具体取决于模板参数的数据类型。我声明了一个帮助程序模板结构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;