具有不同返回类型的显式专用化模板类成员函数

explicit specialization template class member function with different return type

本文关键字:函数 成员 专用 返回类型      更新时间:2023-10-16

我正在尝试将一些C++代码从Windows移植到Solaris(Unix)。有一些模板代码需要更改。我正在使用Solaris的编译器CC,g ++应该有同样的问题。

我有一个特定的代码部分引入了一些麻烦。它们简化如下:

#include <exception>
#include <cmath>
#include <string>
#include <iostream>
// define the "not implement" error
class tempException: public std::exception
{
public:
    virtual const char* what() const throw()
    {
        return "not been implemented!";
    }
} nondeferr;
// the template class
template <typename T>
class A
{
public:
    template <typename Val>
    Val getValue(T t) { throw nondeferr; }
    template<>
    double getValue(T t) { return exp( 1.5 * t ); } //Specialize the getValue for double type.
};
// test code
int main()
{
    try
    {
        A<int> testA;
        std::cout << testA.getValue<double>(2) << std::endl;
        std::cout << testA.getValue<std::string>(2) << std::endl;
    }
    catch (tempException& e)
    {
        std::cout << e.what() << std::endl;
    }
return 0;
}

要在 UNIX 中编译此示例代码,会出现编译错误,因为显式专用化不能在 A 类范围内。

这里的 getValue 函数仅与返回类型不同,因此我们不能使用重载方式修改它。

出于某种原因,不允许将具有简单模板变量 T 的类 A 更改为具有双模板变量 T 和 Val 的类 A。当我们尝试使用此基本类时,它将引入很多更改。

我可以知道是否有任何解决方案吗?我目前正在删除getValue函数,将其替换为getDoubleValue...但这也不是那么好。


对于那些感兴趣的人,现在A类看起来像这样:

template <typename T>
class A
{
public:
    // the Get Value we want
    template <typename R>
    R getValue(T t) { return get_value_impl<R>::apply(*this, t); }
    // the general get value struct
    template<typename R, typename = void>
    struct get_value_impl
    {
        static R apply(A a, T t) { throw nondeferr; }
    };
    // partial specialization, which is allowed in std C++
    template <typename S>
    struct get_value_impl<double, S>
    {
        static double apply(A a, T t) { return exp( 1.5 * t ); }
    };
};

背后的逻辑是标准中不允许显式专用化。但是,允许部分专业化。再次感谢Anycorn的出色解决方案。

// the template class
template <typename T>
class A {
    template<>
    double getValue(T t) { return exp( 1.5 * t ); }
};

这是标准不允许的。

做:

template <typename T>
class A {
    template<class R>
    R getValue(T t) { return get_value_impl<double>::apply(*this, t); }
    template<class R, class = void>
    struct get_value_impl; // specialize this
};

不允许在不专门化周围类的情况下专用化成员函数。 Visual Studio允许将其作为扩展。