具有不同返回类型的显式专用化模板类成员函数
explicit specialization template class member function with different return type
我正在尝试将一些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允许将其作为扩展。
相关文章:
- 如何使用指针传递给函数的数组中对象的函数成员
- c++构造函数成员初始化:传递参数
- 创建 std::函数,它返回具有函数成员值的变量.分段错误
- 如何在C++通过公共函数访问私有函数成员?
- 解释了构造函数成员初始化列表
- 调用std::函数成员时内存损坏
- 是否可以为模板类的模板函数成员设置别名?
- 捕获 lambda 函数C++成员变量
- 构造函数成员初始值设定项跨成员列出,安全吗?
- 获取与在模板参数中传递的函数成员类型相同的类
- 如何从公共函数成员访问地图私有成员
- C 构造函数成员分配优化
- 使用命名空间进行函数成员定义
- 函数成员作为 CUDA 内核的参数
- 模板基类函数成员的别名
- 函数成员中用于void和继承的enable_if
- 头文件中是否定义了一个很长的Class函数成员
- 类内/构造函数成员初始化
- 使用指向部分专用函数成员的指针自动填充向量
- 指向函数成员的指针