2015-10-12 60 views
0

对于我想在模板中使用的不同数据类型,我有几个函数,这取决于模板参数的数据类型。我宣布了一个辅助模板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的解决方案将非常受欢迎。

回答

2

您可以使用:

static auto constexpr func = f; 

static auto constexpr func = g; 

我在G ++,当我试图不constexpr编译有以下错误。

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(); 
    } 
}; 
+0

谢谢!不幸的是,我现在坚持使用VS2013,它不支持constexpr。任何其他想法?我编辑了答案并为你+1了。 – Rostislav

+0

所以我想没有办法重复功能签名(他们当然在我的真实代码中更加精细)。它是否正确? – Rostislav

+0

@Rostislav,由于VS2013不支持所有的C++ 11功能,我觉得很难建议一个不同的工作。这对我没有快速访问VS2013没有帮助。 –

1

如果你不能使用自动,你可能仍然使用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;